【问题标题】:How to mock mixin during unit test using vue-test-utils and jest?如何在单元测试期间使用 vue-test-utils 和 jest 模拟 mixin?
【发布时间】:2019-08-07 19:55:35
【问题描述】:

我想在 Test.vue 中测试 testMethod,但是 testMethod 使用了从 App.js 导入的 mixin。

Test.vue

<script>
    export default {
        methods: {
            testMethod() {
                return 'get'+this.getTestMixin();
            }
        },
    };
</script>

mixins/common.js

export default {
    methods: {
        getTestMixin() {
            return 'test';
        },
    },
};

如何模拟 mixin?我试图像下面那样模拟 mixin 但失败了,知道我在哪里做错了吗?

function getTestMixin() {
    return 'test';
}

const localVue = createLocalVue()
localVue.mixin(getTestMixin)

const wrapper = shallowMount(Test, {
    localVue,
})

错误信息如下:

TypeError: Cannot read property 'props' of undefined
  46 | beforeEach(() => {
> 47 |  wrapper = shallowMount(Test, {
     |          ^
  48 |      localVue,
  49 |  });
  50 | });

【问题讨论】:

    标签: unit-testing vue.js


    【解决方案1】:

    如果在浅挂载之前替换 Mixin,则可以模拟它们。比如:

    const localVue = createLocalVue();
    
    const mockMixin = {
      methods: {
        mixinMethod() {
            return 'test';
        },
      }
    }
    
    const MockedTestComponent = { ...TestComponent, mixins: [mockMixin] };
    
    const wrapper = shallowMount(MockedTestComponent, {
      localVue,
    });
    
    expect(wrapper.vm.mixinMethod()).toEqual('test');
    

    【讨论】:

      【解决方案2】:

      使用 Vue 3 并使用 Vue Test Utils,这只是使用 Jest 模拟单个方法的问题。

          const wrapper = mount(Test, {
              global: {
                  mixins: [common],
              },
          } as any)
      
          jest.spyOn(wrapper.vm, 'getTestMixin').mockImplementation()
      

      所以 testMethod() 的返回值将只是 'get'

      请注意,Jest 模拟它而不关心该方法在 mixin 上,而不是在 Vue 组件上。

      【讨论】:

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