Testing is essential for making certain React apps are steady and bug-free. Common instruments like Jest and React Testing Library make testing React parts easy.
Let’s have a look at the way to write nice checks for React:
render Part
Render the element right into a check atmosphere utilizing render
from React Testing Library:
import { render } from '@testing-library/react';
import Button from './Button';
check('shows button textual content', () => {
const { getByText } = render(<Button>Click on</Button>);
count on(getByText('Click on')).toBeInTheDocument();
});
This renders the element just about for testing.
Hearth Occasions
Simulate consumer occasions like clicks with fireEvent
:
check('calls onClick prop on click on', () => {
const onClick = jest.fn();
const { getByText } = render(<Button onClick={onClick}>Click on</Button>);
fireEvent.click on(getByText('Click on'));
count on(onClick).toHaveBeenCalledTimes(1);
});
Assertion Matchers
Use matchers like toBeInTheDocument
to make assertions:
// Assertion passes
count on(getByText('Click on')).toBeInTheDocument();
// Assertion fails
count on(getByText('Click on')).not.toBeInTheDocument();
Mock Features
Spy on callbacks with mock capabilities:
const handleChange = jest.fn();
// work together with element
count on(handleChange).toHaveBeenCalledWith('enter worth');
This permits asserting operate calls.
Abstract
- Use render to mount parts
- Hearth occasions to simulate interplay
- Make assertions with matchers
- Spy on callbacks with mock capabilities
Automated testing leads to sturdy React parts you possibly can refactor with confidence.