Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
})
like image 603
heyr Avatar asked Apr 18 '19 13:04

heyr


1 Answers

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")
like image 146
tony19 Avatar answered Oct 12 '22 06:10

tony19