Maybe I missed something, but is there a way to test EventListeners?
I have following component
export default {
props: { ..... },
created () {
if (this.closeOnEsc) { // boolean prop.
window.addEventListener('keydown', this._closeOnEsc)
}
},
beforeDestroy () {
if (this.closeOnEsc) {
window.removeEventListener('keydown', this._closeOnEsc)
}
},
methods: {
close () {
this.$emit('close')
},
_closeOnEsc (e) {
if (this.isOpen && e.keyCode === 27) {
this.close()
}
}
}
}
It is working in storybook so far, that if you set the prop to true and press esc that the close event is emitted.
It works also if I test against the button which has @click="close()"
Here are the tests
it('should emit close event on button click', () => {
const wrapper = shallow(Modal, {
propsData: {
isOpen: true
}
})
expect(wrapper.props().isOpen).toBe(true)
wrapper.find('.modal-close').trigger('click')
expect(wrapper.emitted().close).toBeTruthy()
})
it('should emit close event on esc', () => {
const wrapper = shallow(Modal, {
propsData: {
isOpen: true,
closeOnEsc: true
}
})
expect(wrapper.props().closeOnEsc).toBe(true)
wrapper.trigger('keydown.esc')
expect(wrapper.emitted().close).toBeTruthy()
})
The first test with the button is working. However not the second one.
Hi, thanks for the detailed bug report.
This is related to this bug — https://github.com/vuejs/vue-test-utils/issues/215. It should be fixed in the next beta release 😀
Awesome! Thanks! :pray:
I am not sure if it was related to that issue, but the following example works for me:
it('should emit close event on esc', () => {
const component = {
created () {
window.addEventListener('keydown', this._closeOnEsc)
},
methods: {
close () {
this.$emit('close')
},
_closeOnEsc (e) {
if (e.keyCode === 27) {
this.close()
}
}
}
}
const wrapper = mount(component, {
attachToDocument: true
})
wrapper.trigger('keydown.esc')
expect(wrapper.emitted().close).to.be.ok
})
@apertureless make sure you use attachToDocument: true when working with window and DOM-Events.
Much thanks @wtho ! 🙏
attachToDocument did the trick.
Most helpful comment
I am not sure if it was related to that issue, but the following example works for me:
@apertureless make sure you use
attachToDocument: truewhen working withwindowand DOM-Events.