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

时间:2019-03-17 06:56:14

标签: unit-testing vue.js

我想在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,但失败了,知道我在哪里做错了吗?

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 | });

1 个答案:

答案 0 :(得分:0)

如果在浅安装之前更换 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');