vue.js - Vue Test Utils & Vue 3:如何有效地测试 onKeyStroke() 事件
问题描述
我目前正在使用vueuse/core
的onKeyStroke
事件传感器。
onKeyStroke(
'c',
(e) => {
e.preventDefault()
showAsterisms.value = false
showConstellations.value = !showConstellations.value
},
{
target: document
}
)
我希望通过以下方式测试此功能:
it('Constellations Should Be Visible', async () => {
wrapper.trigger('keydown', {
key: 'c'
})
await wrapper.vm.$nextTick()
const canvas = wrapper.find('canvas')
const canvasAttributes = canvas.attributes()
expect(canvasAttributes['data-constellations']).toBe('true')
})
包装器是已安装组件的地方:
const wrapper = mount(MyComponent, {
props: {
...
}
})
然后我在画布上有以下绑定属性:
<canvas :data-constellations="showConstellations" />
但是,使用此设置,似乎此特定设置的画布 elmenent 上的 data-constellations 属性始终设置为默认 false,并且在 keyPress 之后它不会更新......
有人可以告诉我我需要做什么才能让它工作吗?
解决方案
您onKeyStroke
将事件侦听器附加到文档(通过{ target: document }
选项),因此测试必须在文档上调度keydown
事件:
it('Constellations Should Be Visible', async () => {
const wrapper = shallowMount(MyComponent)
// simulate keypress on document
const event = new KeyboardEvent('keydown', { key: 'c' })
document.dispatchEvent(event)
await wrapper.vm.$nextTick()
const canvas = wrapper.find('canvas')
const canvasAttributes = canvas.attributes()
expect(canvasAttributes['data-constellations']).toBe('true')
})
推荐阅读
- reactjs - 如何获取组件的 React.Children
- arrays - 打印 True 或 False
- iis - 经典 ASP - 重写/重定向 url 更改 ApplicationPool?
- python - \b 在 \ 之后。不抓期
- html - 添加内容时的“自动滚动”div
- azure - 如何使用 Azure AZ 覆盖/添加参数
- java - JsonDeserialize 在 Kotlin 中根据请求引发 JSON 解析错误
- codenameone - 适用于 Android TV 的 Codename One APK 清单:构建提示
- azure - 从 Azure CosmosDB Graph (GREMLIN API) 中的两个顶点获取信息
- python-3.x - GCS 文件锁定查询