Jest 单元测试:Mock Vue 组件并传递参数
要mock一个Vue组件并向组件传值,你可以使用Jest提供的jest.mock函数来模拟组件,并使用shallowMount来创建一个包含模拟组件的包装器。然后,你可以使用setProps方法来向组件传递值。\n\n下面是一个示例:\n\njavascript\nimport { shallowMount } from '@vue/test-utils';\nimport MyComponent from '@/components/MyComponent.vue';\nimport AnotherComponent from '@/components/AnotherComponent.vue';\n\njest.mock('@/components/AnotherComponent.vue', () => ({\n // 在这里定义模拟组件的行为和属性\n template: '<div>Mocked AnotherComponent</div>',\n props: ['propA'],\n}));\n\ndescribe('MyComponent', () => {\n it('renders AnotherComponent with propA value', () => {\n const wrapper = shallowMount(MyComponent);\n // 使用setProps方法向模拟组件传递值\n wrapper.findComponent(AnotherComponent).vm.$emit('update:propA', 'mocked value');\n expect(wrapper.findComponent(AnotherComponent).props('propA')).toBe('mocked value');\n });\n});\n\n\n在上面的示例中,我们使用jest.mock来模拟AnotherComponent组件,并定义了一个简单的模板和一个propA属性。然后,我们使用shallowMount来创建MyComponent的包装器。在测试中,我们使用setProps方法向模拟组件传递一个值,并使用expect断言来验证propA是否正确传递给了模拟组件。\n\n请注意,我们使用wrapper.findComponent来查找模拟组件,并使用vm.$emit来触发update:propA事件来传递值。
原文地址: https://www.cveoy.top/t/topic/pKXY 著作权归作者所有。请勿转载和采集!