8

I've added 'attachToDocument', but I still can't trigger a keyup event on window.

my dependencies' version:

"@vue/test-utils": "^1.0.0-beta.29"

"vue": "2.5.18"

<template lang="pug">
div
  h1 123
</template>
<script>
export default {
  mounted() {
    window.addEventListener('keyup', this.handleKeyup)
  },
  beforeDestroy() {
    window.removeEventListener('keyup', this.handleKeyup)
  },
  methods: {
    handleKeyup() {}
  }
}
</script>
import { mount } from '@vue/test-utils'
import test from '@/views/test.vue'

describe('just test', () => {
  it('handle keyup', () => {
    const wrapper = mount(test, {
      attachToDocument: true
    })
    const handleKeyup = jest.fn()
    wrapper.setMethods({ handleKeyup })
    wrapper.trigger('keyup')
    expect(handleKeyup).toHaveBeenCalled()
  })
})

'handleKeyup' should have been called.

I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this.

Billyyyyy3320
  • 176
  • 1
  • 1
  • 9

2 Answers2

12

You set up your event listener in the mounted hook so when you call wrapper.setMethods the event listener is already set up with the original empty function. Also wrapper.trigger will dispatch the event on the Vue instance but you set up your event listener on the window object. Try the following ..

import { mount } from '@vue/test-utils'
import test from '@/views/test.vue'

describe('just test', () => {
  it('handle keyup', () => {
    const handleKeyup = jest.fn()
    const wrapper = mount(test, {
        methods: { handleKeyup }
    })
    window.dispatchEvent(new Event('keyup'))
    expect(handleKeyup).toHaveBeenCalled()
  })
})
Husam Ibrahim
  • 6,999
  • 3
  • 16
  • 28
  • 2
    This basically tests if `mounted()` works. What needs to be tested is that the listener attaches to the `window` object, that it gets called on `keyup` and gets removed on beforeDestroy. So [attachToDom](https://vue-test-utils.vuejs.org/api/options.html#attachtodocument) should probably be used. Another option is to use a `window` mock having `addEventListener` and `removeEventListener` as `jest.fn()`s for this test suite. – tao Apr 18 '19 at 07:13
0

For if someone need answer for this:

It's method working for me:

First you need register removeEventListener of global mode with defineProperty

For example:

Object.defineProperty(window, 'removeEventListener', {
    value: jest.fn(),
})

After we write the test

  it('When beforeMounted is executed', async () => {

    await wrapper.destroy()
    expect(window.removeEventListener).toHaveBeenCalled()
    expect(window.removeEventListener).toHaveBeenCalledWith(
      'keyup',
      wrapper.vm.keyUp
   )
})
Kevin Mendez
  • 651
  • 5
  • 10