Search code examples
javascriptvue.jsjestjsvue-test-utils

How to mock Web API in VueTestUtils / Jest?


I want to set a unit test on a very simple Vue Component with the default Vue Test Utils plugin coupled to Jest Framework.

On a click of a button, the handler calls 2 methods:

  • emitEvent(): to emit an event (actual target of my test),

  • effectUI(): for UI effect (using the Web Animations API). This animation is applied on each 'particle' of a 'particles' array. I do not wish to test this part (yet), but this is the one which is problematic.

I works fine when I run the component. No warnings, no errors.

But when I run the test, it passes... with console.error stating that 'particle.animate' is not a function.

I have tried:

  • first, to do nothing special: since the EffectUI() method has nothing to do with the click event (except they are called by the same handler) so maybe they do...

  • then, to mock the "animate" function: with no result so far. I assume the issue comes from the Web API method not being recognized. I may be completely wrong.

Code of method called from component click's handler:

effectUI() {
  let particles = this.$el.querySelectorAll('span.particle')
  particles.forEach(particle => { particle.animate(...) }
}

Code of test file:

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

describe('ButtonParticles.vue', () => {
  const wrapper = mount(ButtonParticles)

  const animStub = jest.fn()

  it('should trigger `clicked` event when user clicks on button', () => {
    let particles = wrapper.findAll('.particle')
    particles.wrappers.forEach(particle => {
      particle.animate = animStub 
    })
    wrapper.find('button').trigger('click')
    expect(wrapper.emitted().clicked).toBeTruthy()
  })

})

Expected results would be to get no console.error

Actual results are: [Vue warn]: Error in v-on handler: "TypeError: particle.animate is not a function" (+ stack trace)

Anyone can help me understand what's happening? Thanks!


Solution

  • In your test, particle is a wrapper. Try particle.element.animate = animStub