首页 > 解决方案 > 如何在 VueTestUtils / Jest 中模拟 Web API?

问题描述

我想在一个非常简单的 Vue 组件上设置一个单元测试,其中默认的 Vue Test Utils 插件与 Jest 框架耦合。

单击按钮时,处理程序会调用 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 warn]: Error in v-on handler: "TypeError:particle.animate is not a function" (+ stack trace)

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

标签: javascriptvue.jsjestjsvue-test-utils

解决方案


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


推荐阅读