要mock一个Vue组件并向组件传值,你可以使用Jest提供的jest.mock函数来模拟组件,并使用shallowMount来创建一个包含模拟组件的包装器。然后,你可以使用setProps方法来向组件传递值。

下面是一个示例:

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

jest.mock('@/components/AnotherComponent.vue', () => ({
  // 在这里定义模拟组件的行为和属性
  template: '<div>Mocked AnotherComponent</div>',
  props: ['propA'],
}));

describe('MyComponent', () => {
  it('renders AnotherComponent with propA value', () => {
    const wrapper = shallowMount(MyComponent);
    // 使用setProps方法向模拟组件传递值
    wrapper.findComponent(AnotherComponent).vm.$emit('update:propA', 'mocked value');
    expect(wrapper.findComponent(AnotherComponent).props('propA')).toBe('mocked value');
  });
});

在上面的示例中,我们使用jest.mock来模拟AnotherComponent组件,并定义了一个简单的模板和一个propA属性。然后,我们使用shallowMount来创建MyComponent的包装器。在测试中,我们使用setProps方法向模拟组件传递一个值,并使用expect断言来验证propA是否正确传递给了模拟组件。

请注意,我们使用wrapper.findComponent来查找模拟组件,并使用vm.$emit来触发update:propA事件来传递值

jest 单元测试 如何mock一个 vue组件并向组件传值

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

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