Vue单元测试PrimeVue复选框:点击后断言选中状态失败
PrimeVue复选框单元测试断言失败解决方案
问题背景
在Vue 3项目中使用PrimeVue的Checkbox组件,结合vitest、@testing-library/vue和@testing-library/user-event编写单元测试时,点击复选框后验证其选中状态的断言失败。元素可正常定位,但断言checked属性为true时返回null。
组件代码
<div class="field-checkbox"> <Checkbox role="checkbox" :aria-label="`Select all students in class ${props.className}`" @change="selectAllChecked()" v-model="selectAll" :binary="true" /> <label>Select All</label> </div>
测试用例
it("checkbox test", async() => { const ariaLabel = `Select all students in class ${mockProps.className}`; const checkbox = screen.getByRole("checkbox", { name: ariaLabel }); await userEvent.click(checkbox); expect(checkbox.getAttribute('checked')).toBe(true) });
报错信息
AssertionError: expected null to be true // Object.is equality - Expected "true" + Received "null"
解决方法
原因分析
PrimeVue的Checkbox组件并非直接通过原生checked属性标识选中状态,而是通过aria-checked属性或内部状态维护,直接获取checked属性会返回null。
方案1:使用@testing-library内置断言(推荐)
@testing-library提供了专门用于复选框选中状态的断言toBeChecked(),无需手动操作属性:
it("checkbox test", async() => { const ariaLabel = `Select all students in class ${mockProps.className}`; const checkbox = screen.getByRole("checkbox", { name: ariaLabel }); await userEvent.click(checkbox); expect(checkbox).toBeChecked(); });
方案2:验证aria-checked属性
PrimeVue的Checkbox选中时会设置aria-checked="true",可以直接断言该属性:
it("checkbox test", async() => { const ariaLabel = `Select all students in class ${mockProps.className}`; const checkbox = screen.getByRole("checkbox", { name: ariaLabel }); await userEvent.click(checkbox); expect(checkbox.getAttribute('aria-checked')).toBe('true'); });
方案3:验证组件v-model绑定值
如果需要验证组件内部状态,可以通过组件实例获取selectAll的值:
it("checkbox test", async() => { const wrapper = render(YourComponent, { props: mockProps }); const ariaLabel = `Select all students in class ${mockProps.className}`; const checkbox = screen.getByRole("checkbox", { name: ariaLabel }); await userEvent.click(checkbox); expect(wrapper.vm.selectAll).toBe(true); });
内容的提问来源于stack exchange,提问作者user4094935
相关产品推荐
相关产品推荐

