8

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()
})
tony19
  • 125,647
  • 18
  • 229
  • 307
heyr
  • 5,514
  • 11
  • 34
  • 55

2 Answers2

9

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")
tony19
  • 125,647
  • 18
  • 229
  • 307
0

Vue test utils has a built in way to mock methods -

const wrapper = shallowMount(attendeesList,{
   testMethod:jest.fn()
})

the simplest way to solve your problem is to move the code in the mounted hook into a method, stub that using the code above and call it from your hook.

Alon Bar David
  • 1,757
  • 14
  • 15