Madhu Sudhan Subedi
Madhu Sudhan Subedi

Reputation: 509

How to mock Vue Mixins during unit testing using vue-test-utils and jest?

I have read the documentation for vue-test-utils and Jest, but I am still unsure about how to properly mock Vue mixins in a Vue component and test the component.

Upvotes: 30

Views: 25717

Answers (3)

Edward
Edward

Reputation: 5248

There are two ways:

  1. You can use createLocalVue, and register a mixin on that localVue class:
const localVue = createLocalVue()
localVue.mixin(myMixin)

const wrapper = shallow(Post, {
    localVue,
})
  1. You can pass mixins in the mounting options:
const wrapper = shallow(Post, {
    mixins: [myMixin],
})

Upvotes: 23

Paul F. Wood
Paul F. Wood

Reputation: 1775

For those using Vue 3 with Vue Test Utils, then you just need to mock the individual method, for example with Jest. Pass in your myMixin as normal, and then spy on the method you want to mock:

    const wrapper = mount(Post, {
        global: {
            mixins: [myMixin],
        },
    } as any)

    jest.spyOn(wrapper.vm, 'myMixinMethodToMock').mockImplementation()

Note that Jest mocks it without caring that the method is on the mixin, not the Vue component.

Upvotes: 1

onekiloparsec
onekiloparsec

Reputation: 2063

I managed to mock the mixin methods with jest spies like this:

/// MyComponent.spec.js
describe('MyComponent', () => {
  let wrapper
  let localVue
  let store
  let spies = {}
  
  beforeEach(async () => {
    spies.mixinMethodName = jest.spyOn(MyComponent[1].methods, 'spies.mixinMethodName')
    ({ localVue, store } = (... custom factory ...)
    wrapper = await shallowMount(MyComponent, { localVue, store })
  })

  it('check mixin methods calls', () => {
    expect(spies.mixinMethodName).toHaveBeenCalled()
  })
})

Of course the spies object and its attached method can be customized as your wish.

The weakness of this method is that it relies on the order of the mixins entered in the real Vue component. For this example, this looks like:

/// MyComponent.vue
<script>
  export default {
    components: { ...components... },
    mixins: [mixin1, mixin2ToBeTested],
    data () {}
    ....
}
</script>

Upvotes: 0

Related Questions