We test props and events to make sure components get the right data and respond correctly when users interact.
0
0
Props and event testing in Cypress
Introduction
When you want to check if a component shows the right text or data passed as props.
When you want to verify a button click triggers the correct event handler.
When you want to confirm a form input updates state through events.
When you want to test if a child component receives the correct props from its parent.
Syntax
Cypress
cy.mount(<Component propName={value} />)
cy.get('selector').click()
cy.get('selector').should('have.text', 'expected text')
cy.spy(object, 'method')
cy.wrap(spy).should('have.been.called')Use cy.mount() to render components with props in Cypress component testing.
Use cy.spy() to watch event handler calls and cy.wrap() to assert they happened.
Examples
This checks if the Button component shows the label passed as a prop.
Cypress
cy.mount(<Button label="Click me" />) cy.get('button').should('have.text', 'Click me')
This tests if clicking the button calls the onClick event handler.
Cypress
const onClick = cy.spy().as('clickSpy') cy.mount(<Button onClick={onClick} />) cy.get('button').click() cy.get('@clickSpy').should('have.been.called')
Sample Program
This test suite mounts a Button component twice: once to check the label prop, and once to check the click event calls the handler.
Cypress
import React from 'react' import { mount } from 'cypress/react' function Button({ label, onClick }) { return <button onClick={onClick}>{label}</button> } describe('Button component', () => { it('shows the label prop', () => { mount(<Button label="Press me" />) cy.get('button').should('have.text', 'Press me') }) it('calls onClick when clicked', () => { const onClick = cy.spy().as('clickSpy') mount(<Button label="Press me" onClick={onClick} />) cy.get('button').click() cy.get('@clickSpy').should('have.been.called') }) })
OutputSuccess
Important Notes
Always use clear selectors like element tags or data attributes for locating elements.
Spies help confirm event handlers run without changing component code.
Mount components fresh in each test to avoid state leaks.
Summary
Props testing checks if components display or use data correctly.
Event testing confirms user actions trigger the right functions.
Cypress spies and mount make these tests easy and reliable.