【问题标题】:How to mock Vue Mixins during unit testing using vue-test-utils and jest?如何在单元测试期间使用 vue-test-utils 和 jest 模拟 Vue Mixins?
【发布时间】:2018-04-29 23:13:59
【问题描述】:

我阅读了 3 次 vue-utils-test 文档和 jest 文档,但我不知道如何在 vue 组件中模拟 vue mixins 并测试该组件。

【问题讨论】:

    标签: unit-testing vue.js jestjs mixins


    【解决方案1】:

    有两种方式:

    1. 您可以使用 createLocalVue,并在该 localVue 类上注册一个 mixin:
    const localVue = createLocalVue()
    localVue.mixin(myMixin)
    
    const wrapper = shallow(Post, {
        localVue,
    })
    
    1. 您可以在安装选项中传递mixins
    const wrapper = shallow(Post, {
        mixins: [myMixin],
    })
    

    【讨论】:

    • 如果我想模拟组件使用的插件,下一步是什么?
    • 这对我不起作用,我在 vue-test-utils 代码中看不到任何与此相关的内容。我如何模拟我注册到 SPC 的 mixin?无论我做什么,mixin 的 mounted 方法总是运行。
    • 那你怎么调用方法呢? this.myMethod?
    • @Edd 这些技术与全局注册的 mixins 与本地导入和注册的 mixins 有何关系?我想尽可能简单地模拟本地使用的 mixin 的所有实例,但不确定最佳方法
    • 提供的答案不会模拟 mixin。它只解释了如何在 localVue 实例中安装 mixin。
    【解决方案2】:

    我设法用这样的玩笑间谍来模拟 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>
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2019-08-07
        • 2018-09-01
        • 2021-05-07
        • 2021-11-13
        • 1970-01-01
        • 2019-05-28
        • 2018-03-15
        • 2021-09-11
        • 2018-08-06
        相关资源
        最近更新 更多