React testing library has replaced Enzyme as the new standard for testing React components. It renders components to the virtual DOM, queries for an element in the DOM and then makes assertions on that element.
import { render, screen } from '@testing-library/react';
import App from './App';
test('A very basic test', () => {
render(<App />);
const textElement = screen.getByText(/hello world/i);
expect(textElement).toBeInTheDocument();
});
I really like the way we structure tests with React testing library. Render the component, get some element, assert on the element. Very intuitive.
Whenever we test behaviour like button clicks, we make sure of the user-event library.
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import App from './App';
test('Button click', () => {
render(<App />);
const buttonElement = screen.getByRole('button', { name: /click me/i });
userEvent.click(buttonElement);
const textElement = screen.getByText(/some text/i);
expect(textElement).toBeInTheDocument();
});
In the above test, we click a button and hopefully some new text appears in the screen.
I wrote an elaborate article covering more scenarios. Love to hear your feedback on it.
Top comments (0)