DEV Community

Alan Schio
Alan Schio

Posted on

Testing Hooks on Vue 2 (or Options API)

Have you ever spent hours thinking how could you test a method called on mount?
First lets say we have this component:

export default {
  name: 'MyCustomComponent',
  mounted() {
    this.calledOnMount()
  },
  methods: {
    calledOnMount() {}
  }
}
Enter fullscreen mode Exit fullscreen mode

We want to make sure the calledOnMount will be called, using @vue/test-utils and vitest/jest there are two main ways to test validate it:

  • toHaveBeenCalled
  • toBeCalled

But the work with a spy function and usually we write tests like this:

import { mount } from '@vue/test-utils'
import MyCustomComponent from '../MyCustomComponent.vue'

describe('MyCustomComponent.vue', () => {
  const wrapper = mount(MyCustomComponent)
  spyOn(wrapper.vm, 'calledOnMount')
})
Enter fullscreen mode Exit fullscreen mode

When calling the mount it already runs the mounted lifecicly, so, even adding a spy it will always fail.

  • toHaveBeenCalled -> we can't intercept the mount proccess to add a spy on here
  • toBeCalled -> the function has already be called

But calm down, there is a way to test it, for sure!
We had to bind the spy by accessing the .vue component and its options.methods such:

import MyCustomComponent from '../MyCustomComponent.vue'
type MyCustomComponentType = {
  options: { methods: { calledOnMount: () => void } }
}
vi.spyOn(
  (MyCustomComponent as unknown as MyCustomComponentType).options.methods,
  'calledOnMount'
)
Enter fullscreen mode Exit fullscreen mode

This way you dont have to intercept the wrapper functions, but the component signature function.
Once the mounted component is like a new "instance" of a "class" component, the spy we add on the .vue, will also works with the mounted component on test.

describe('MyCustomComponent.vue', () => {
  const wrapper = mount()
  it('Should remove scroll event listener on destroy', async () => {
    expect(
      (MyCustomComponent as unknown as MyCustomComponentType).options.methods
        .calledOnMount
    ).toHaveBeenCalled()
  })
})

Enter fullscreen mode Exit fullscreen mode

Now you can easy test your functions and everything you do on mount.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay