0
0
Cypresstesting~5 mins

Mounting React components in Cypress

Choose your learning style9 modes available
Introduction

Mounting React components lets you test them in a real browser environment. It helps you check if the component works as expected when used in an app.

You want to test how a React button behaves when clicked.
You need to check if a form component shows error messages correctly.
You want to verify that a list component renders all items properly.
You want to test component interaction with user input.
You want to catch bugs before releasing your React app.
Syntax
Cypress
import { mount } from 'cypress/react';

mount(<YourComponent prop1={value1} />);

Use mount() to render your React component inside Cypress.

Pass your component as JSX inside mount().

Examples
This mounts a simple Button component with a label prop.
Cypress
import { mount } from 'cypress/react';
import Button from './Button';

mount(<Button label="Click me" />);
This mounts a Form component without props to test its default behavior.
Cypress
import { mount } from 'cypress/react';
import Form from './Form';

mount(<Form />);
Sample Program

This test mounts a simple Hello component and checks if it shows the correct greeting.

Cypress
import { mount } from 'cypress/react';
import React from 'react';

function Hello({ name }) {
  return <h1>Hello, {name}!</h1>;
}

describe('Hello component', () => {
  it('shows greeting with name', () => {
    mount(<Hello name="Alice" />);
    cy.contains('Hello, Alice!').should('be.visible');
  });
});
OutputSuccess
Important Notes

Always import mount from cypress/react to mount React components.

Use Cypress commands like cy.contains() to check what the component renders.

Mounting helps test components isolated from the full app.

Summary

Mount React components in Cypress using mount().

This lets you test component rendering and behavior in a browser.

Use assertions to check if the component shows expected content.