Bootstrap-Vue 组件上的触发事件(测试)

Trigger Event on Bootstrap-Vue Component (testing)

我正在 vue 应用程序中编写测试(使用 Jest)。在测试某个组件时,我需要在复选框上触发更改事件(我正在使用 BFormCheckbox)。

当我 select 使用 select 的复选框或实际复选框的计算结果为 ('.custom-control-input') 时,我可以通过下面的测试。但是,我想使用实际组件的名称 (BFormCheckbox),我觉得这样更容易理解。有什么办法可以做到这一点吗?

      it('is triggered by clicking a phase checkbox', () => {
        // I would like to write:
        // const phaseCheckbox = wrapper.find(BFormCheckbox);

        // However, I can only get the following to work:
        const phaseCheckbox = wrapper.find('.custom-control-input');

        // this is true for both selectors
        expect(phaseCheckbox.exists()).toBe(true);

        phaseCheckbox.trigger('change');

        // this fails for wrapper.find(BFormCheckbox)
        expect(togglePhaseSpy).toHaveBeenCalled();
      });

由于 <input type="checkbox"> 嵌套在附加的 HTML 标记中(由 Bootstrap v4 定义),使用以下内容访问隐藏的输入:

const phaseCheckbox = wrapper.find(BFormCheckbox).find('input')

这不会限制您使用内部元素类名,因为它们会根据 <b-form-checkbox> 的渲染样式模式(即默认自定义复选框、开关样式复选框、按钮样式复选框、或普通模式复选框)。

Jest documentation 显示了如何按照您的要求进行操作的示例。

组件构造函数:

import Foo from '../components/Foo';

const wrapper = mount(<MyComponent />);
expect(wrapper.find(Foo)).to.have.lengthOf(1);

组件显示名称:

const wrapper = mount(<MyComponent />);
expect(wrapper.find('Foo')).to.have.lengthOf(1);