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

29

我已经阅读了vue-test-utils和Jest的文档,但我仍然不确定如何正确地模拟Vue混入(mixins)在Vue组件中并测试该组件。

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],
})

3
如果我想嘲笑组件使用的插件,下一步应该怎么做? - 葛厚德
2
这对我不起作用,而且我在vue-test-utils代码中没有看到与此相关的内容。我如何模拟我注册到SPC中的mixin?无论我做什么,mixin的“mounted”方法总是运行。 - mlohbihler
4
那么你如何调用这些方法?使用 this.myMethod 吗? - Jalil
1
@Edd,这些技术与全局注册的mixin和本地导入和注册的mixin有什么关系?我想尽可能简单地模拟所有本地使用的mixin实例,但不确定最佳方法是什么。 - Damon
7
提供的答案并没有嘲笑 mixin。它只是解释如何在 localVue 实例中安装 mixin。 - onekiloparsec
1
谁有Vue3的解决方案?Vue3没有本地Vue。 - Lonyui

1

对于使用Vue 3和Vue Test Utils的人来说,你只需要模拟单个方法,例如使用Jest。像往常一样传递你的myMixin,然后监听你想要模拟的方法:

    const wrapper = mount(Post, {
        global: {
            mixins: [myMixin],
        },
    } as any)

    jest.spyOn(wrapper.vm, 'myMixinMethodToMock').mockImplementation()

注意,Jest对此进行模拟时不关心该方法是否在混入项上而不是Vue组件上。

0
我成功地使用Jest Spy来模拟混入方法,代码如下:

/// 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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接