如何在 Vue Test Utils / Jest 中模拟 Web API?

How to mock Web API in VueTestUtils / Jest?

我想在一个非常简单的 Vue 组件上设置一个单元测试,使用默认的 Vue Test Utils 插件耦合到 Jest Framework。

单击按钮时,处理程序调用 2 个方法:

我 运行 组件时工作正常。没有警告,没有错误。

但是当我 运行 测试时,它通过了... console.error 说明 'particle.animate' 不是一个函数。

我试过:

从组件点击处理程序调用的方法代码:

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

测试文件代码:

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()
  })

})

预期的结果是没有console.error

实际结果是:[Vue 警告]:v-on 处理程序错误:"TypeError: particle.animate is not a function"(+ 堆栈跟踪)

任何人都可以帮助我了解发生了什么? 谢谢!

在您的测试中,particle 是一个包装器。尝试 particle.element.animate = animStub