Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 740
Billyyyyy3320 Avatar asked Apr 18 '19 02:04

Billyyyyy3320


1 Answers

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()
  })
})
like image 75
Husam Ibrahim Avatar answered Oct 29 '22 13:10

Husam Ibrahim