Although Webpack might not be your preferred bundler, with tools like Vite gaining significant community support, you may still encounter projects where configuring Jest and React Testing Library with Webpack is necessary.
To configure Jest and React Testing Library in this application, follow these steps:
1. Install Jest and React Testing Library
Install Jest and React Testing Library as development dependencies:
npm install --save-dev jest @testing-library/react @testing-library/jest-dom
2. Configure Babel
Ensure Babel is set up correctly to work with Jest. Add or update your babel.config.js
or .babelrc
file with the following:
{
"presets": ["@babel/preset-env", "@babel/preset-react", "@babel/preset-typescript"]
}
Install the necessary Babel presets if not already installed:
npm install --save-dev @babel/preset-env @babel/preset-react @babel/preset-typescript
3. Add a Jest Configuration File
Create a jest.config.js
file in the root of your project:
module.exports = {
testEnvironment: "jsdom",
moduleNameMapper: {
"\\.(css|scss)$": "identity-obj-proxy"
},
transform: {
"^.+\\.(js|jsx|ts|tsx)$": "babel-jest"
}
};
4. Install Additional Dependencies
Install the following dependencies for handling CSS modules and Jest transformations:
npm install --save-dev babel-jest identity-obj-proxy
5. Create Test Files
Ensure your test files follow the naming convention *.test.js
or *.test.tsx
. Place them in the same directories as your components or within a dedicated __tests__
folder.
Example: src/App.test.js
import { render, screen } from "@testing-library/react";
import App from "./App";
test("renders the App component", () => {
render(<App />);
const linkElement = screen.getByText(/Task Timer/i);
expect(linkElement).toBeInTheDocument();
});
6. Update Package.json Scripts
Add a script for running tests in your package.json
:
"scripts": {
"test": "jest"
}
Run your tests with:
npm test
7. Configure Webpack for CSS Modules
Ensure your Webpack configuration supports CSS modules and Jest compatibility:
{
test: /\.module\.(css|scss)$/,
use: [
"style-loader",
{
loader: "css-loader",
options: {
modules: {
localIdentName: "[name]__[local]__[hash:base64:5]",
},
esModule: true,
},
},
"sass-loader"
],
}
8. Verify the Setup
Run your tests to ensure everything is working:
npm test
Fix any issues or errors encountered during this step.
9. Optional: Add a Coverage Report
Enable code coverage by adding the following to your Jest configuration:
module.exports = {
collectCoverage: true,
collectCoverageFrom: ["src/**/*.{js,jsx,ts,tsx}", "!src/index.js"],
coverageReporters: ["html", "text"]
};
Run tests with coverage:
npm test -- --coverage
This will generate a coverage report that you can review for untested parts of your codebase.
Something to Discuss?
Have questions, ideas, or feedback? Let's talk! Visit hoshdev.com/contact and start the conversation.
I'm here to help you tackle challenges and create amazing solutions.
Top comments (0)