Anand Verdhan
Anand Verdhan

Reputation: 1

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?

Upvotes: 0

Views: 984

Answers (2)

Anand Verdhan
Anand Verdhan

Reputation: 1

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();
    }
}

Upvotes: 0

Fody
Fody

Reputation: 31904

You are triggering on the body element, but the event listener is on document. Perhaps it bubbles, but if not it's worth trying

cy.document()
  .trigger('keydown', { keyCode: 39 })

Upvotes: 1

Related Questions