使用 Vue Test Utils,如何检查按钮是否被禁用?

Jon*_*n_B 12 vue.js jestjs vue-test-utils vue-testing-library

我正在测试 Vue 组件,但在测试按钮的禁用状态时遇到问题。如何在测试中访问按钮的禁用状态?

我尝试过使用,.attributes()但在这种情况下,该方法仅返回未由v-bind. SubmitButton.attributes().disabled总是null

成分

<button
  id="edit-resource-modal-submit"
  class="btn btn-sm btn-primary modal-button"
  :disabled="loadingResource || !formValid"
  @click="submit"
>
  Save
</button>
Run Code Online (Sandbox Code Playgroud)

测试

describe('Disables buttons if', () => {
  beforeEach(async() => {
    await wrapper.setProps({ isModalOpen: true });
  });
  it('modal is loading', async() => {
    wrapper.vm.loadingResource = true;
    const SubmitButton = wrapper.find('#edit-resource-modal-submit');
    expect(SubmitButton.exists()).toBe(true);
    expect(SubmitButton.attributes().disabled).toBe('true');
  });
});

Run Code Online (Sandbox Code Playgroud)

.attributes() 仅返回

{
  id: 'edit-resource-modal-submit',
  class: 'btn btn-sm btn-primary modal-button'
}
Run Code Online (Sandbox Code Playgroud)

ton*_*y19 17

选项 1:检查disabled属性

在 Vue 2 中,当元素实际被禁用时,该disabled属性被设置为"disabled"(not )。"true"在 Vue 3 中,它被设置为空字符串。当元素被启用时,属性本身是未定义的(即属性中不存在)。

为了与两个版本的 Vue 兼容,测试可以只检查属性是否disabled已定义。另请注意,测试应等待微勾选(通过await wrapper.vm.$nextTick())以允许属性更改(wrapper.vm.loadingResource = true)在禁用按钮时生效:

const wrapper = shallowMount(MyComponent)

// update prop, and wait a tick to allow it to take effect
wrapper.vm.loadingResource = true
await wrapper.vm.$nextTick()

const button = wrapper.find('#edit-resource-modal-submit')
expect(button.attributes().disabled).toBeDefined() 
Run Code Online (Sandbox Code Playgroud)

选项 2:检查disabled财产

测试可以disabled直接从元素引用本身读取属性,该属性由测试包装器的element属性公开:

const wrapper = shallowMount(MyComponent)

// update prop, and wait a tick to allow it to take effect
wrapper.vm.loadingResource = true
await wrapper.vm.$nextTick()

const button = wrapper.find('#edit-resource-modal-submit')
expect(button.element.disabled).toBe(true) 
Run Code Online (Sandbox Code Playgroud)

Vue 2 演示

Vue 3 演示


The*_*iaz 8

对于 vue-test-utils 和 vue 3,@tony19 的答案也有效。然而,它使用 vue-test-utils for vue 2 的旧 api。

正如您所看到的,如果该元素已启用,则返回值attributes()不包含属性。disabled所以我建议通过以下方式进行测试:

expect(SubmitButton.attributes('disabled')).toBeUndefined(); // enabled
expect(SubmitButton.attributes('disabled')).toBe("") // disabled
Run Code Online (Sandbox Code Playgroud)