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.