Search code examples
vue.jsvue-test-utils

Emit keydown event with key modifier on a stub in vue-test-utils


I have a auto-stubbed child component with a keydown event with a .down modifier. I want to trigger this event in my test.

Somewhere in component.vue:

<child-component @keydown.down="myFn()" />

Somewhere in component.spec.js:

 // I expect the keydown.down event to be triggered:
 wrapper.find({name: 'child-component'}).vm.$emit('keydown.down')

This doesn't work. The only way I was able to trigger the event is when i remove the modifier .down, or if I add a .native modifier to the event. Unfortunately I'm unable to use the .native modifier.

Other things I've tried:

wrapper.find({name: 'child-component'}).trigger('keydown.down')

wrapper.find({name: 'child-component'}).vm.$emit('keydown', {keyCode: 40})


Solution

  • The solution is to supply a KeyboardEvent as the second parameter of the $emit function, with the keyCode of the key modifier. So if we want to trigger a keydown.down event, we can do so as such:

    wrapper.find({name: 'child-component'}).vm.$emit(
        'keydown', 
        new KeyboardEvent('keydown', {
            keyCode: 40
        })
    )