Test using Jest and React Testing Library
Here's a step-by-step guide to create a simple React app and test it using Jest and React Testing Library:
Step 1: Set up a new React App
First, make sure you have Node.js and npm installed on your machine. Then, you can use create-react-app
to quickly set up a new React project:
npx create-react-app my-react-app
Replace my-react-app
with the name you want for your project.
Step 2: Navigate to the Project Directory
cd my-react-app
Step 3: Create a Simple Component
Let's create a simple Button component that we'll later test:
Create a file named Button.js
inside the src
directory with the following content:
import React from 'react';
const Button = ({ label, onClick }) => {
return (
<button onClick={onClick}>
{label}
</button>
);
};
export default Button;
Step 4: Write Tests for the Component
Create a file named Button.test.js
inside the src
directory with the following content:
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import Button from './Button';
test('renders button with correct text', () => {
render(<Button label="Click me" />);
const buttonElement = screen.getByText('Click me');
expect(buttonElement).toBeInTheDocument();
});
test('calls onClick prop when clicked', () => {
const onClickMock = jest.fn();
render(<Button label="Click me" onClick={onClickMock} />);
const buttonElement = screen.getByText('Click me');
fireEvent.click(buttonElement);
expect(onClickMock).toHaveBeenCalledTimes(1);
});
Step 5: Run Tests
Run the tests using the following command:
npm test
Step 6: Review Test Results
Jest will run the tests, and you should see output indicating whether the tests passed or failed.
Step 7: Explore Further
You can further explore Jest and React Testing Library to write more advanced tests for your React components. You can test various scenarios, including rendering props, handling user interactions, testing async behavior, and more.
Step 8: Start the React App (Optional)
If you want to see your React app in action, you can start the development server using the following command:
npm start
Then, open your browser and go to http://localhost:3000
to view your React app.
By following these steps, you've created a simple React app and tested it using Jest and React Testing Library. You can now continue building your app and adding more tests as needed.
Leave a Comment