Verify isolated rendering and behavior of a UI component
Preconditions (2)
✅ Expected Result: The component renders correctly and responds to interactions without affecting or depending on other UI parts
import { mount } from 'cypress/react'; import { useState } from 'react'; // Simple Button component that toggles text on click function ToggleButton() { const [on, setOn] = useState(false); return ( <button data-testid="toggle-btn" onClick={() => setOn(!on)}> {on ? 'ON' : 'OFF'} </button> ); } describe('ToggleButton component isolation test', () => { it('renders and toggles text without affecting outside', () => { mount(<ToggleButton />); // Verify initial state cy.get('[data-testid=toggle-btn]').should('have.text', 'OFF'); // Click button to toggle cy.get('[data-testid=toggle-btn]').click(); // Verify toggled state cy.get('[data-testid=toggle-btn]').should('have.text', 'ON'); // Verify no other elements exist outside component cy.get('body').children().should('have.length', 1); }); });
This test mounts the ToggleButton component alone using cy.mount(), which isolates it from the rest of the UI. We use a data-testid attribute for a stable selector to find the button. The test first checks the initial text is 'OFF'. Then it clicks the button and verifies the text changes to 'ON'. Finally, it asserts that no other elements outside the component are present, confirming isolation. This shows component testing isolates UI units by testing them alone without external dependencies or side effects.
Now add data-driven testing with 3 different initial states for the ToggleButton component
cy.mount() better than testing it inside the full app?Pass the test and this pattern moves unknown