0
0
Cypresstesting~15 mins

Component test setup in Cypress - Build an Automation Script

Choose your learning style9 modes available
Setup and render a React component for testing
Preconditions (2)
Step 1: Import the Button component into the test file
Step 2: Use the Cypress mount command to render the Button component
Step 3: Verify that the Button component is visible on the page
✅ Expected Result: The Button component is rendered and visible in the Cypress test runner
Automation Requirements - Cypress with @cypress/react
Assertions Needed:
Verify the Button component is visible after mounting
Best Practices:
Use the mount command from @cypress/react to render components
Keep tests isolated and independent
Use semantic selectors or component props for locating elements
Automated Solution
Cypress
import React from 'react';
import { mount } from '@cypress/react';
import Button from '../../src/components/Button';

describe('Component test setup for Button', () => {
  it('should render the Button component and verify visibility', () => {
    mount(<Button label="Click me" />);
    cy.get('button').should('be.visible').and('contain.text', 'Click me');
  });
});

The test imports React and the mount function from @cypress/react to render the component inside Cypress.

The Button component is imported from the project source.

Inside the test, mount() renders the Button with a label prop.

Then, Cypress uses cy.get('button') to find the button element and asserts it is visible and contains the correct text.

This setup ensures the component renders correctly and is ready for further interaction tests.

Common Mistakes - 3 Pitfalls
Not importing the mount function from @cypress/react
{'mistake': "Using generic selectors like 'div' instead of semantic selectors", 'why_bad': 'Generic selectors are brittle and can break easily if the component structure changes.', 'correct_approach': "Use semantic selectors like 'button' or data attributes for stable element targeting."}
Not verifying component visibility after mounting
Bonus Challenge

Now add data-driven testing with 3 different button labels

Show Hint