0
0
Cypresstesting~5 mins

Component test setup in Cypress

Choose your learning style9 modes available
Introduction

Setting up component tests helps you check small parts of your app work right before combining them. It saves time and finds bugs early.

You want to test a single button or form without loading the whole app.
You need to check if a component shows the right text or reacts to clicks.
You want to run tests faster by focusing on one piece at a time.
You want to catch errors in a component before it breaks the whole page.
Syntax
Cypress
import { mount } from 'cypress/react18';

describe('ComponentName', () => {
  beforeEach(() => {
    mount(<ComponentName />);
  });

  it('does something', () => {
    // test code here
  });
});

Use mount() to load the component inside Cypress for testing.

beforeEach() runs before every test to set up the component fresh.

Examples
This example mounts a Button component with a label and checks if the label appears.
Cypress
import { mount } from 'cypress/react18';
import Button from './Button';

describe('Button component', () => {
  beforeEach(() => {
    mount(<Button label="Click me" />);
  });

  it('shows the correct label', () => {
    cy.contains('Click me').should('exist');
  });
});
This example mounts an Input component and tests typing text into it.
Cypress
import { mount } from 'cypress/react18';
import Input from './Input';

describe('Input component', () => {
  beforeEach(() => {
    mount(<Input placeholder="Enter name" />);
  });

  it('accepts user input', () => {
    cy.get('input').type('Alice').should('have.value', 'Alice');
  });
});
Sample Program

This test mounts a Greeting component with a name prop and checks if the greeting text shows correctly.

Cypress
import { mount } from 'cypress/react18';
import Greeting from './Greeting';

describe('Greeting component', () => {
  beforeEach(() => {
    mount(<Greeting name="Bob" />);
  });

  it('displays the greeting message', () => {
    cy.contains('Hello, Bob!').should('exist');
  });
});
OutputSuccess
Important Notes

Always mount your component fresh in beforeEach() to avoid test interference.

Use clear and simple selectors like text or role for better test reliability.

Component tests run faster than full app tests because they load less code.

Summary

Component test setup uses mount() to load a component inside Cypress.

Use beforeEach() to prepare the component before each test.

This helps test small parts quickly and catch bugs early.