首页 > 解决方案 > 如何在单元测试期间使用 vue-test-utils 和 jest 模拟 mixin?

问题描述

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

测试.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-testingvue.js

解决方案


如果在浅挂载之前替换 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');

推荐阅读