You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jest+Vue Test Utils:如何断言window事件监听器的回调函数?

解决方案

先排查代码中存在的几个关键问题,对应修正后即可完成验证:

1. 测试代码的拼写错误

你在测试中通过jest.spyOn监听的方法名是manageTimes,但组件中实际定义的方法是manageTimers,这是导致断言失败的直接原因。

2. 组件data选项的写法错误

Vue 2中data必须是返回对象的函数,而非直接给this赋值,否则会导致数据绑定异常,影响后续方法执行:

// 修正后的组件data部分
data() {
  return {
    timer: null,
    stoppedForce: false
  }
},

3. 修正后的测试代码

以下是可以正确验证manageTimers被调用的测试代码:

import myComponent from './Component'
import { shallowMount } from '@vue/test-utils'

describe('Component test', () => {
  it('should trigger manageTimers when window resizes', () => {
    // 挂载组件
    const wrapper = shallowMount(myComponent)
    
    // 对manageTimers方法创建间谍
    const manageTimersSpy = jest.spyOn(wrapper.vm, 'manageTimers')
    
    // 触发window的resize事件
    window.dispatchEvent(new Event('resize'))
    
    // 断言resize事件监听已注册
    expect(window.addEventListener).toHaveBeenCalledWith('resize', expect.any(Function))
    // 断言manageTimers被调用
    expect(manageTimersSpy).toHaveBeenCalled()
  })
})

额外说明

  • 如果需要验证resetTimer是否被调用(或timer是否被设置),需要确保组件的$el中不存在[data-wrapper-adTVU]元素(因为manageTimers会根据这个条件分支执行不同逻辑),可以通过shallowMount的配置或手动操作DOM来测试分支逻辑。
  • 测试完成后建议清除事件监听,避免影响其他测试:
afterEach(() => {
  window.removeEventListener('resize', wrapper.vm.manageTimers)
})

内容的提问来源于stack exchange,提问作者Julieta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 18:10:26