Stub lifecycyle hooks in Vue

It's quite a common pattern to initialise a component in a created() or mounted() hook. The problem is that these hooks will execute every time a component is mounted as part of the tests and it may not be what you want.

export default {
  methods: {
    initialise() {
      // heavy initialisation logic
    }
  },
  mounted() {
    this.initialise()
  }
}

When using Vue Test Utils and mount() or shallowMount() the first idea that comes to mind is to override the initialise method:

import { shallowMount } from '@vue/test-utils';
import Component from './Component'

let wrapper = shallowMount(Component, {
  methods: {
    initialise() {
      // does nothing, but really?
    }
  }
});

The gotcha is that mounting a component in this way will ignore the method override and still execute the lifecycle hooks, since it all happens at a very early stage of component initialisation.

To actually deal with this problem, we're going to have to be more sneaky and use a sinon stub:

import { shallowMount } from '@vue/test-utils';
import Component from './Component'
import sinon from 'sinon'

let wrapper

describe('Component', () => {
  beforeEach(() => {
    sinon.stub(Component, 'mounted');
    wrapper = shallowMount(Component)
  })

  afterEach(() => {
    Component.mounted.restore()
  })

  // test cases
});