如何在单元测试期间使用 vue-test-utils 和 jest 模拟 mixin?

jim*_*mmy 7 unit-testing vue.js

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

测试.vue

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

mixins/common.js

export default {
    methods: {
        getTestMixin() {
            return 'test';
        },
    },
};
Run Code Online (Sandbox Code Playgroud)

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

function getTestMixin() {
    return 'test';
}

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

const wrapper = shallowMount(Test, {
    localVue,
})
Run Code Online (Sandbox Code Playgroud)

错误信息如下:

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

gol*_*das 3

如果 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');
Run Code Online (Sandbox Code Playgroud)