【发布时间】:2018-04-29 23:13:59
【问题描述】:
我阅读了 3 次 vue-utils-test 文档和 jest 文档,但我不知道如何在 vue 组件中模拟 vue mixins 并测试该组件。
【问题讨论】:
标签: unit-testing vue.js jestjs mixins
我阅读了 3 次 vue-utils-test 文档和 jest 文档,但我不知道如何在 vue 组件中模拟 vue mixins 并测试该组件。
【问题讨论】:
标签: unit-testing vue.js jestjs mixins
有两种方式:
const localVue = createLocalVue()
localVue.mixin(myMixin)
const wrapper = shallow(Post, {
localVue,
})
mixins:const wrapper = shallow(Post, {
mixins: [myMixin],
})
【讨论】:
mounted 方法总是运行。
this.myMethod?
我设法用这样的玩笑间谍来模拟 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>
【讨论】:
对于那些使用 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 组件上。
【讨论】: