【问题标题】:Vue Test Utils & Vue 3: How to effectively test onKeyStroke() eventVue Test Utils & Vue 3:如何有效地测试 onKeyStroke() 事件
【发布时间】:2021-11-26 17:49:14
【问题描述】:

我目前正在使用vueuse/coreonKeyStroke 事件传感器。

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 之后它不会更新...

有人可以告诉我我需要做些什么才能使它正常工作吗?

【问题讨论】:

    标签: vue.js jestjs vuejs3


    【解决方案1】:

    您的onKeyStroke 将事件侦听器附加到文档(通过{ target: document } 选项),因此测试必须dispatch 文档上的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')
    })
    

    demo

    【讨论】:

    • 啊啊啊我明白了。是的,我在想trigger() 是否附加到正确的节点。我想在这个意义上我们也需要await wrapper.vm.$nextTick(),因为我们不能使用await wrapper.trigger()。谢谢你!
    猜你喜欢
    • 2019-04-17
    • 2019-10-24
    • 2021-04-03
    • 2021-02-17
    • 2019-07-16
    • 2018-07-07
    • 2018-10-28
    • 2018-09-28
    • 2020-12-01
    相关资源
    最近更新 更多