| π Jest | β React Testing Library |
|---|
Testing is a crucial aspect of software development that ensures the reliability and stability of your application. In React applications, Jest and React Testing Library are popular choices for writing tests. This tutorial will guide you through setting up the Jest and React Testing Library for testing React components, specifically focusing on configuring Jest to handle ES modules and writing tests for a simple React component.
-
Step 1:
- Install Jest and React Testing Library as development dependencies.
npm install --save-dev jest @testing-library/react @testing-library/jest-dom
-
Step 2:
- Ensure Jest is configured to handle ES modules by installing
babel-jest,@babel/core, and@babel/preset-env
npm install --save-dev babel-jest @babel/core @babel/preset-env
- Ensure Jest is configured to handle ES modules by installing
-
Step 3:
- Create a Babel configuration file (
.babelrcorbabel.config.json) in the project root.
{ "presets": ["@babel/preset-env", "@babel/preset-react"] } - Create a Babel configuration file (
-
Step 4:
- Update
package.jsonto include a test script that executes Jest.
"scripts": { "test": "jest" }
- Update
-
Step 1:
- Install
jest-environment-jsdom
npm install --save-dev @testing-library/jest-dom
- Install
-
Step 2:
- Update Jest configuration in
package.jsonto usejest-environment-jsdom
{ "jest": { "testEnvironment": "jest-environment-jsdom" } } - Update Jest configuration in
-
Step 3:
- Install
jest-environment-jsdom
npm install --save-dev @testing-library/jest-dom
- Install
-
Step 1:
- Create a simple React component (
eg,. App.js).
import React from "react"; function App() { return ( <div> <h1>Software Testing With Jest</h1> </div> ); }export default App;
- Create a simple React component (
-
Step 2:
- Write a test for the App component (
eg,. App.test.js)
import { render, screen } from '@testing-library/react'; import '@testing-library/jest-dom/extend-expect'; import App from '../path/to/App'; test("First test case for App Component", () => { render(<App />); const text = screen.getByText("Software Testing With Jest"); expect(text).toBeInTheDocument(); }); - Write a test for the App component (
