
Unit Testing with React.js
17 February, 2023
0
0
1
Contributors
Introduction to Jest
Jest is a popular testing framework for React apps, and it can be used for unit testing as well as other types of testing. It provides us with an interface to interact with the application and several methods to expect
at particular outcome or throw an error when that does not happen.
Testing with Jest
Here's a general approach to performing React unit testing with Jest:
- Set up Jest: If you haven't already, you'll need to install Jest using a package manager like npm or Yarn. You'll also need to create a configuration file for Jest, which can be done using the
jest.config.js
file. - Write your test file: Create a file with the
.test.js
extension, or add.test
to the end of your component file name. For example, if you have aButton
component, you can create aButton.test.js
file for testing it. In this file, you can import your component and write tests for its functionality. - Write your tests: In your test file, you can use Jest's built-in testing functions like
describe
andit
to write tests for your component. For example, you might write a test to make sure that yourButton
component is rendering correctly. - Use Jest to run your tests: Once you've written your test file, you can use Jest to run your tests. You can do this by running the
jest
command in your terminal or by configuring your code editor to run tests automatically.
Here's an example of a basic unit test for a React component using Jest:
import React from 'react';
import { render } from '@testing-library/react';
import Button from './Button';
describe('Button component', () => {
it('renders a button with the correct text', () => {
const { getByText } = render(<Button text="Click me" />);
const buttonElement = getByText('Click me');
expect(buttonElement).toBeInTheDocument();
});
});
Explanation
The describe
block that we see here can be considered as a logical grouping of several tests. In this case, it is testing the button component. The it
block here describes a single test case.
In this example, we're testing that the Button
component renders a button with the correct text (Click me). We're using the render
function from the @testing-library/react
package to render the component, and the getByText
function to find the button element with the correct text.
Finally, we're using the Jest expect
function to check that the button element is in the document. If that button is not found, the same line of code will case the test case to fail and as a result, the test - renders a button with the correct text
will fail.