Search code examples
reactjsjestjsevent-handlingcypress

cypress not able to trigger functions added by document.addEventListener on keypress


I have a react app in which I add an event listener on document dynamically which executes on pressing right/left arrow key.

It works when I try to trigger it manually in cypress open-ct by pressing the arrow key but when I write it in a test to trigger it like cy.get('body').trigger('keydown', { keyCode: 39 });, the function does not trigger, is there any other way to trigger functions added by document.addEventListener ?

componentDidUpdate(prevProps) {

      if (something something) {
        document.addEventListener('keydown', this.handleLeftRightKeys);
      } else {
        document.removeEventListener('keydown', this.handleLeftRightKeys);
      }
}

handleLeftRightKeys(event) {
    if (event.key === 'ArrowLeft') {
      this.prev();
    } else if (event.key === 'ArrowRight') {
      this.next();
    }
}

I want these prev() and next() functions to be trigerred from the cypress test file. How to do that?


Solution

  • Found the answer. Had to add keyCode to the eventListener.

    changed

    handleLeftRightKeys(event) {
        if (event.key === 'ArrowLeft') {
          this.prev();
        } else if (event.key === 'ArrowRight') {
          this.next();
        }
    }
    

    to

    handleLeftRightKeys(event) {
        if (event.key === 'ArrowLeft' || event.keyCode === 37) {
          this.prev();
        } else if (event.key === 'ArrowRight' || event.keyCode === 39) {
          this.next();
        }
    }