Billyyyyy3320
Billyyyyy3320

Reputation: 186

How to trigger a window event during unit testing using vue-test-utils

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.

Upvotes: 9

Views: 15551

Answers (2)

Kevin Mendez
Kevin Mendez

Reputation: 668

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
   )
})

Upvotes: 0

Husam Elbashir
Husam Elbashir

Reputation: 7177

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()
  })
})

Upvotes: 13

Related Questions