0
0
Cypresstesting~15 mins

cy.trigger() for custom events in Cypress - Build an Automation Script

Choose your learning style9 modes available
Trigger a custom event and verify event handler execution
Preconditions (2)
Step 1: Visit the web page containing the button.
Step 2: Use cy.get() to select the button with id 'custom-event-btn'.
Step 3: Trigger the custom event 'myCustomEvent' on the button using cy.trigger().
Step 4: Verify that the button text changes to 'Event Triggered!'.
✅ Expected Result: The button text changes to 'Event Triggered!' after the custom event 'myCustomEvent' is triggered.
Automation Requirements - Cypress
Assertions Needed:
Verify the button text changes to 'Event Triggered!' after triggering the custom event.
Best Practices:
Use cy.get() with id selector for element selection.
Use cy.trigger() to fire the custom event.
Use should() assertion to verify the text change.
Avoid hardcoded waits; rely on Cypress automatic waits.
Automated Solution
Cypress
describe('Custom Event Trigger Test', () => {
  it('should trigger custom event and verify button text change', () => {
    cy.visit('/');
    cy.get('#custom-event-btn')
      .trigger('myCustomEvent')
      .should('have.text', 'Event Triggered!');
  });
});

This test visits the page, selects the button by its id, triggers the custom event 'myCustomEvent' on it, and then asserts that the button's text changes to 'Event Triggered!'.

Using cy.get('#custom-event-btn') ensures we select the correct element. The cy.trigger('myCustomEvent') fires the custom event as if it happened naturally. The should('have.text', 'Event Triggered!') assertion waits automatically until the text changes, making the test reliable without manual waits.

Common Mistakes - 3 Pitfalls
{'mistake': 'Using incorrect selector like class instead of id when the element has an id.', 'why_bad': 'This can select the wrong element or no element, causing the test to fail or be flaky.', 'correct_approach': "Use the exact id selector with cy.get('#custom-event-btn') to select the button reliably."}
{'mistake': 'Triggering the event on the wrong element or without selecting any element.', 'why_bad': "The event won't fire on the intended element, so the event handler won't run and the test will fail.", 'correct_approach': 'Always chain cy.trigger() after cy.get() to ensure the event fires on the correct element.'}
Using cy.wait() with fixed time instead of relying on Cypress automatic waits.
Bonus Challenge

Now add data-driven testing to trigger the custom event on three different buttons with ids 'custom-event-btn1', 'custom-event-btn2', and 'custom-event-btn3', verifying each changes text to 'Event Triggered!'.

Show Hint