heyr
heyr

Reputation: 5774

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

Upvotes: 9

Views: 13967

Answers (2)

tony19
tony19

Reputation: 138226

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")

Upvotes: 10

Alon Bar David
Alon Bar David

Reputation: 1727

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.

Upvotes: 0

Related Questions