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.
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()
})
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With