Sipann
Sipann

Reputation: 138

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:

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:

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!

Upvotes: 1

Views: 676

Answers (1)

Renaud
Renaud

Reputation: 1300

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

Upvotes: 1

Related Questions