javascript - 如何在 VueTestUtils / Jest 中模拟 Web API?
问题描述
我想在一个非常简单的 Vue 组件上设置一个单元测试,其中默认的 Vue Test Utils 插件与 Jest 框架耦合。
单击按钮时,处理程序会调用 2 个方法:
emitEvent():发出一个事件(我测试的实际目标),
effectUI():用于 UI 效果(使用 Web Animations API)。此动画应用于“粒子”阵列的每个“粒子”。我不想测试这部分(还),但这是有问题的部分。
我运行组件时工作正常。没有警告,没有错误。
但是当我运行测试时,它通过了...... console.error 指出'particle.animate'不是一个函数。
我努力了:
首先,什么都不做:因为 EffectUI() 方法与 click 事件无关(除了它们被同一个处理程序调用)所以也许他们做......
然后,模拟“动画”功能:到目前为止没有结果。我认为问题来自未被识别的 Web API 方法。我可能完全错了。
从组件单击的处理程序调用的方法代码:
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)
任何人都可以帮助我了解发生了什么?谢谢!
解决方案
在您的测试中,particle
是一个包装器。尝试particle.element.animate = animStub
推荐阅读
- postgresql - 在 TEIID 中使用默认值会引发 TeiidSQLException
- python - 使用openCV导出openGL纹理时出现异常
- javascript - 如何加快我的 vue 项目的画廊部分?
- azure - 是否可以在 Azure Pipelines YAML 中定义具有依赖关系的资源
- angular - Angular Ag Grid - 单元格渲染按钮删除行?
- php - php: UPDATE SET 函数不更新表
- amazon-web-services - 将 Athena ODBC 驱动程序与 credential_source Ec2InstanceMetadata 一起使用
- c++ - 为什么 C++20 中的空结构没有隐式宇宙飞船运算符?
- file-type - geany 自定义文件类型 .svrf 用于语法高亮
- c++ - 转换、强制转换和强制转换有什么区别?