代码之家  ›  专栏  ›  技术社区  ›  Madhu Sudhan Subedi

如何在单元测试期间使用Vue测试UTIL和jest模拟Vue混合?

  •  27
  • Madhu Sudhan Subedi  · 技术社区  · 7 年前

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

    3 回复  |  直到 6 年前
        1
  •  21
  •   yuriy636    6 年前

    有两种方法:

    1. 您可以使用 createLocalVue ,并在该localVue类上注册一个mixin:
    const localVue = createLocalVue()
    localVue.mixin(myMixin)
    
    const wrapper = shallow(Post, {
        localVue,
    })
    
    1. 你可以通过 mixins 在安装选项中:
    const wrapper = shallow(Post, {
        mixins: [myMixin],
    })
    
        2
  •  0
  •   onekiloparsec    3 年前

    我设法用这样的玩笑间谍来模拟混合方法:

    /// 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>
    
        3
  •  0
  •   Paul F. Wood kelloti    3 年前

    对于那些使用Vue 3和Vue测试UTIL的用户,您只需要模拟单个方法,例如使用Jest。把你的 myMixin 正常情况下,然后监视要模拟的方法:

        const wrapper = mount(Post, {
            global: {
                mixins: [myMixin],
            },
        } as any)
    
        jest.spyOn(wrapper.vm, 'myMixinMethodToMock').mockImplementation()
    

    注意,Jest对其进行了模拟,而不关心该方法是否在mixin上,而不是Vue组件上。