0
0
Cypresstesting~15 mins

Props and event testing in Cypress - Build an Automation Script

Choose your learning style9 modes available
Verify component renders with correct props and handles click event
Preconditions (2)
Step 1: Mount the 'Button' component with the prop label='Submit'
Step 2: Check that the button text is 'Submit'
Step 3: Click the button
Step 4: Verify that the click event handler is called once
✅ Expected Result: The button displays the label 'Submit' and the click event handler is triggered exactly once when clicked
Automation Requirements - Cypress with @cypress/react
Assertions Needed:
Verify button text matches the label prop
Verify click event handler is called once on click
Best Practices:
Use cy.mount() to mount React components
Use data-cy attributes or semantic selectors for locating elements
Use Cypress spies to verify event handler calls
Avoid hardcoded waits; use Cypress commands chaining
Automated Solution
Cypress
import React from 'react';
import { mount } from '@cypress/react';
import Button from '../../src/components/Button';

describe('Button component props and event testing', () => {
  it('renders with correct label and handles click event', () => {
    const onClickSpy = cy.spy().as('onClickSpy');

    mount(<Button label="Submit" onClick={onClickSpy} />);

    cy.get('button').should('have.text', 'Submit');

    cy.get('button').click();

    cy.get('@onClickSpy').should('have.been.calledOnce');
  });
});

The test imports React and the mount function from Cypress React plugin to render the Button component.

We create a spy function onClickSpy to track clicks on the button.

The Button is mounted with the label prop set to 'Submit' and the onClick prop set to the spy.

We assert the button's text matches the label prop.

Then we simulate a click on the button and verify the spy was called exactly once.

This ensures the component renders props correctly and handles events as expected.

Common Mistakes - 3 Pitfalls
{'mistake': "Using generic selectors like 'button' without data attributes", 'why_bad': 'It can select multiple buttons or wrong elements, making tests flaky', 'correct_approach': "Add data-cy attributes to the button and select with cy.get('[data-cy=submit-button]')"}
Not using spies to verify event handlers
Hardcoding waits like cy.wait(1000)
Bonus Challenge

Now add data-driven testing with 3 different label props and verify each renders correctly and triggers click event

Show Hint