vue-test-utils
和 Jest 的文档,但我仍然不确定如何在 Vue 组件中正确模拟 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()
请注意,Jest 模拟它时并不关心该方法是在 mixin 上,而不是在 Vue 组件上。
我设法用这样的玩笑间谍来模拟 mixin 方法:
/// 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 组件中输入的 mixin 的顺序。对于这个例子,这看起来像:
/// MyComponent.vue
<script>
export default {
components: { ...components... },
mixins: [mixin1, mixin2ToBeTested],
data () {}
....
}
</script>