Streamlining React.js Testing: A Beginner’s Guide to Simple Button Testing with Cypress
Let’s create a simple React component called ButtonComponent
which renders a button with a given label.
// ButtonComponent.tsx
import React from 'react';
interface ButtonProps {
label: string;
onClick: () => void;
}
const ButtonComponent: React.FC<ButtonProps> = ({ label, onClick }) => {
return (
<button onClick={onClick}>
{label}
</button>
);
};
export default ButtonComponent;
Now, let’s write Cypress tests to ensure the ButtonComponent
behaves as expected.
Test Case 1: Rendering Correctly
Ensure the button component renders with the correct label:
// cypress/integration/button.spec.ts
describe('ButtonComponent tests', () => {
beforeEach(() => {
cy.visit('/');
});
it('renders button with correct label', () => {
cy.get('button').should('have.text', 'Click me');
});
});
Test Case 2: Triggering onClick Event
Verify that the onClick
event is triggered when the button is clicked:
// cypress/integration/button.spec.ts
describe('ButtonComponent tests', () => {
beforeEach(() => {
cy.visit('/');
});
it('triggers onClick event when button is clicked', () => {
const onClickStub = cy.stub().as('onClickStub');
cy.window().then(win => {
win.onClickStub = onClickStub;
});
cy.get('button').click().then(() => {
cy.get('@onClickStub').should('have.been.calledOnce');
});
});
});
Run Cypress Tests:
Execute Cypress tests to ensure they pass as expected:
npx cypress run
or open Cypress Test Runner:
npx cypress open
Conclusion:
With Cypress, testing React.js projects with TypeScript becomes a breeze. Leveraging its intuitive API and real-time feedback, you can write robust test suites to ensure code reliability and quality in your applications.
Happy testing!