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

Vue Test Utils测试Vue3中vueuse的onKeyStroke事件不生效如何解决?

问题解决方法

根因分析

你在onKeyStroke配置中指定了事件监听目标为全局document对象,但测试代码中调用wrapper.trigger('keydown')只会将事件触发在组件的根元素上,事件没有传递到document,因此监听回调全程没有执行,变量自然不会更新。

解决方案

  • 方案1:直接给document触发按键事件(无需修改业务代码,改测试代码即可)
    把测试用例里的wrapper.trigger替换为手动给document派发键盘事件,修改后的测试代码如下:
it('Constellations Should Be Visible', async () => {
  // 直接给document触发keydown事件
  document.dispatchEvent(new KeyboardEvent('keydown', { 
    key: 'c',
    code: 'KeyC',
    bubbles: true,
    cancelable: true
  }))

  await wrapper.vm.$nextTick()

  const canvas = wrapper.find('canvas')
  expect(canvas.attributes()['data-constellations']).toBe('true')
})
  • 方案2:适配单元测试调整业务代码(适合需要隔离全局依赖的场景)
    可以将监听目标作为可配置项注入组件,生产环境传入document,测试环境传入组件根元素,这样测试时直接用wrapper.trigger即可生效:
    业务代码调整示例:
// 组件内接收target参数,默认是document
const keyEventTarget = inject('keyEventTarget', document)
onKeyStroke(
  'c',
  (e) => {
    e.preventDefault()
    showAsterisms.value = false
    showConstellations.value = !showConstellations.value
  },
  {
    target: keyEventTarget
  }
)

测试时传入wrapper根元素:

const wrapper = mount(MyComponent, {
  props: {
    ...
  },
  global: {
    provide: {
      keyEventTarget: wrapper.element
    }
  }
})

注意:如果使用JSDOM作为测试运行环境,部分旧版本不会默认挂载KeyboardEvent的key属性,触发事件时同时传入code: 'KeyC'可以提高兼容性。

内容的提问来源于stack exchange,提问作者Micheal J. Roberts

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 08:15:03