我已经阅读了vue-test-utils
和Jest的文档,但我仍然不确定如何正确地模拟Vue混入(mixins)在Vue组件中并测试该组件。
有两种方法:
localVue
类上注册一个mixin:const localVue = createLocalVue()
localVue.mixin(myMixin)
const wrapper = shallow(Post, {
localVue,
})
mixins
:const wrapper = shallow(Post, {
mixins: [myMixin],
})
对于使用Vue 3和Vue Test Utils的人来说,你只需要模拟单个方法,例如使用Jest。像往常一样传递你的myMixin
,然后监听你想要模拟的方法:
const wrapper = mount(Post, {
global: {
mixins: [myMixin],
},
} as any)
jest.spyOn(wrapper.vm, 'myMixinMethodToMock').mockImplementation()
/// MyComponent.spec.js
describe('MyComponent', () => {
let wrapper
let localVue
let store
let spies = {}
beforeEach(async () => {
spies.mixinMethodName = jest.spyOn(MyComponent[1].methods, 'spies.mixinMethodName')
({ localVue, store } = (... custom factory ...)
wrapper = await shallowMount(MyComponent, { localVue, store })
})
it('check mixin methods calls', () => {
expect(spies.mixinMethodName).toHaveBeenCalled()
})
})
当然,spies
对象及其附加的方法可以根据您的需求进行自定义。
这种方法的弱点在于它依赖于混入项在实际Vue组件中输入的顺序。对于这个例子,它看起来像是:
/// MyComponent.vue
<script>
export default {
components: { ...components... },
mixins: [mixin1, mixin2ToBeTested],
data () {}
....
}
</script>
this.myMethod
吗? - Jalil