0
0
Cypresstesting~15 mins

Mounting React components in Cypress - Build an Automation Script

Choose your learning style9 modes available
Mount a simple React Button component and verify its text
Preconditions (2)
Step 1: Import the Button component into the test file
Step 2: Use Cypress mount command to render the Button component with label='Click Me'
Step 3: Find the button element in the mounted component
Step 4: Verify the button's text is exactly 'Click Me'
✅ Expected Result: The Button component mounts successfully and the button displays the text 'Click Me'
Automation Requirements - Cypress with @cypress/react
Assertions Needed:
Verify the button element exists
Verify the button text equals 'Click Me'
Best Practices:
Use cy.mount() from @cypress/react to mount React components
Use semantic selectors like role or text content for locating elements
Keep tests isolated and focused on one component behavior
Avoid using hardcoded CSS selectors that may change
Automated Solution
Cypress
import React from 'react';
import { mount } from '@cypress/react';
import Button from '../../src/components/Button';

describe('Button component mount test', () => {
  it('mounts Button and checks label text', () => {
    mount(<Button label="Click Me" />);
    cy.get('button').should('exist').and('have.text', 'Click Me');
  });
});

The test imports React and the mount function from @cypress/react. It also imports the Button component to test.

Inside the test, mount() renders the Button with the prop label="Click Me". Then, cy.get('button') finds the button element in the mounted component.

The assertions check that the button exists and its text exactly matches 'Click Me'. This confirms the component rendered correctly with the given prop.

This approach uses Cypress best practices: mounting React components directly, using semantic selectors, and clear assertions.

Common Mistakes - 3 Pitfalls
Using cy.visit() to load a page instead of cy.mount() to mount the component
Selecting elements by brittle CSS classes or IDs that may change
{'mistake': 'Not importing the mount function from @cypress/react', 'why_bad': 'Without mount, the test cannot render React components properly.', 'correct_approach': "Always import mount from '@cypress/react' to mount React components in Cypress tests."}
Bonus Challenge

Now add data-driven testing to mount the Button component with 3 different labels and verify each text

Show Hint