在 Jest 中,可以使用 wrapper.find() 方法找到要模拟输入的输入框元素,并使用 setValue() 方法模拟输入事件。

下面是一个示例,展示了如何在 Vue 单元测试中模拟输入框的输入事件:

import { shallowMount } from '@vue/test-utils';
import MyComponent from '@/components/MyComponent.vue';

describe('MyComponent', () => {
  it('should emit input event on input change', () => {
    const wrapper = shallowMount(MyComponent);
    const input = wrapper.find('input');

    // 模拟输入事件
    input.setValue('Hello, World!');

    // 断言输入框的值
    expect(input.element.value).toBe('Hello, World!');

    // 断言是否触发了input事件
    expect(wrapper.emitted().input).toBeTruthy();
    // 断言input事件的参数
    expect(wrapper.emitted().input[0][0]).toBe('Hello, World!');
  });
});

在这个示例中,我们首先使用 shallowMount 方法创建了一个包裹器 (wrapper) 来包裹我们的组件。然后,使用 wrapper.find('input') 找到了要模拟输入的输入框元素。接下来,使用 input.setValue('Hello, World!') 方法模拟了输入框的输入事件,并使用 expect 断言输入框的值是否与预期值相等。

最后,我们使用 expect(wrapper.emitted().input) 来断言是否触发了 input 事件,并使用 expect(wrapper.emitted().input[0][0]) 断言 input 事件的参数是否与预期值相等。

这样就完成了在 Vue 单元测试中模拟输入框的输入事件的操作。

Jest Vue 单元测试:模拟输入框输入事件

原文地址: https://www.cveoy.top/t/topic/pTWT 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录