0
0
Cypresstesting~5 mins

cy.trigger() for custom events in Cypress

Choose your learning style9 modes available
Introduction
You use cy.trigger() to make your web page act like a user did something, like clicking or typing, but you do it in your test automatically.
When you want to test how your page reacts to a special event that is not a normal click or type.
When you want to check if your page listens and responds correctly to custom events you made.
When you want to simulate user actions that are hard to do with normal commands.
When you want to trigger events on elements that are hidden or disabled for normal user actions.
Syntax
Cypress
cy.get(selector).trigger(eventName, options)
selector is how you find the element on the page.
eventName is the name of the event you want to trigger, like 'click' or a custom event name.
options is an optional object where you can add extra details about the event.
Examples
This triggers a normal click event on the button.
Cypress
cy.get('button').trigger('click')
This triggers a custom event called 'myCustomEvent' on the element with id 'myDiv'.
Cypress
cy.get('#myDiv').trigger('myCustomEvent')
This triggers a keydown event with the Enter key on the input element.
Cypress
cy.get('input').trigger('keydown', { keyCode: 13 })
Sample Program
This triggers a custom event named 'myCustomEvent' on the element with id 'customElement' and sends extra data with it.
Cypress
cy.get('#customElement').trigger('myCustomEvent', { detail: { message: 'Hello' } })
OutputSuccess
Important Notes
Custom events need to be set up in your web page code to listen and respond to them.
You can pass extra information with the event using the options object.
cy.trigger() helps test how your page behaves with events that users might not normally do.
Summary
cy.trigger() lets you simulate user or custom events on page elements.
You can trigger normal or custom events with extra details.
It helps test how your page reacts to different kinds of events.