Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock mixin during unit test using vue-test-utils and jest?

I want to test the testMethod in Test.vue, but testMethod had used mixin which import from App.js.

Test.vue

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

mixins/common.js

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

How to mock the mixin? I tried to mock the mixin like following but failed, any idea where am I doing wrong?

function getTestMixin() {
    return 'test';
}

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

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

error message is like following:

TypeError: Cannot read property 'props' of undefined
  46 | beforeEach(() => {
> 47 |  wrapper = shallowMount(Test, {
     |          ^
  48 |      localVue,
  49 |  });
  50 | });
like image 448
jimmy Avatar asked Mar 17 '19 06:03

jimmy


People also ask

How do you test Vue mixin?

Mixins can be tested by creating a mock component and registering the mixin on the component. Mixins can be applied globally or locally on a component. You can register filters and mixins before running unit tests. You can test filters and mixins in components by testing component output.

How do you use mixin in Vue 3?

As mentioned earlier, a mixin is just a Javascript (or TypeScript) file with a Vue component config object. export default { data() { return { /* data */ } }, methods: { some_method() { } }, // etc. } We can export the component directly (like above), or we can store it in a variable and export that variable.


1 Answers

Mixins can be mocked if they are replaced before shallow mount. Something like:

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');
like image 60
golfadas Avatar answered Oct 15 '22 05:10

golfadas