import { mount } from 'cypress/react'; describe('Button component', () => { it('renders with correct label', () => { mount(<button>Click me</button>); cy.get('button').should('have.text', 'Click me'); }); });
The mount function renders the React component inside the Cypress test runner. The cy.get('button') finds the button element, and the assertion checks its text. Since the button text is 'Click me', the test passes.
Using data-cy attributes is a best practice for Cypress tests because it avoids relying on styling classes or IDs that may change. This makes tests more stable and easier to maintain.
import { mount } from 'cypress/react'; mount(<input value="hello" />);
The have.value assertion checks the value property of input elements. Using contain.text or have.text does not work for input values because inputs do not have inner text. Checking the attribute value may not reflect the current value if changed dynamically.
import { mount } from 'cypress/react'; describe('MyComponent', () => { it('should find the button', () => { cy.get('button').should('exist'); mount(<button>Press</button>); }); });
Cypress commands run asynchronously in order. The cy.get('button') runs before the component is mounted, so no button exists yet. The test fails because it looks for the button too early.
To run component tests with React, Cypress needs to know the framework and bundler to use. The component.devServer config with framework: 'react' and bundler: 'webpack' tells Cypress how to build and serve the components for testing.