Search code examples
vue.jsvuejs2jestjsbabel-jestvue-test-utils

Mock mounted hook Jest testing unit


I am doing some unit testing for components. However, in some components, I have something running on the mounted hook that is making my test fail. I have managed to mock the methods that I do not need. However, I was wondering if there is a workaround mocking the mounted hook itself.

@/components/attendeesList.vue

<template>
  <div>
    <span> This is a test </span> 
  </div>
</template>

JS

<script>
methods: {
    testMethod: function() {
        // Whatever is in here I have managed to mock it
    }
},

mounted: {
    this.testMethod();
}
</script>

Test.spec.js

import { mount, shallowMount } from '@vue/test-utils'
import test from '@/components/attendeesList.vue'

describe('mocks a method', () => {    
  test('is a Vue instance', () => {
  const wrapper = shallowMount(attendeesList, {
    testMethod:jest.fn(),
  })
  expect(wrapper.isVueInstance()).toBeTruthy()
})

Solution

  • Currently, vue-test-utils does not support mocking lifecycle hooks, but you can mock the method called from the mounted hook. In your case, to mock testMethod(), use jest.spyOn:

    const testMethod = jest.spyOn(HelloWorld.methods, 'testMethod')
    const wrapper = shallowMount(HelloWorld)
    expect(testMethod).toHaveBeenCalledWith("hello")