如何使用 vue-test-utils 和 jest 在单元测试期间模拟 Vue Mixins?

问题描述 投票:0回答:3

我已经阅读了

vue-test-utils
和 Jest 的文档,但我仍然不确定如何在 Vue 组件中正确模拟 Vue 混合并测试组件。

javascript vue.js unit-testing jestjs mixins
3个回答
22
投票

有两种方式:

  1. 您可以使用 createLocalVue,并在该
    localVue
    类上注册一个 mixin:
const localVue = createLocalVue()
localVue.mixin(myMixin)

const wrapper = shallow(Post, {
    localVue,
})
  1. 您可以在安装选项中通过
    mixins
const wrapper = shallow(Post, {
    mixins: [myMixin],
})

1
投票

对于那些使用 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 组件上。


0
投票

我设法用这样的玩笑间谍来模拟 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>
© www.soinside.com 2019 - 2024. All rights reserved.