Recently, I got a chance to work on my first typescript project, and my first task was to set up unit test cases. At first glance, it seemed simple enough. I started following random documentation and ChatGPT suggestions, only to end up with a mess. If you’ve experienced GPT giving a solution only to later suggest removing it, you’ll relate to my frustration.
Here, I’ve written one more comprehensive guide on the internet to help fellow developers set up their first unit test environment in a TypeScript project—the right way.
Step 1: Install Required Libraries
Start by installing the necessary libraries to set up a Jest environment:
npm install -D @types/jest @types/react-dom @types/react ts-jest typescript @testing-library/jest-dom @testing-library/react
Step 2: Initialize tsconfig.json
Run the following command to create a tsconfig.json file in your project’s root directory:
ts-jest config:init
Step 3: Configure tsconfig.json
Replace the content of your tsconfig.json file with the following configuration:
{
"compilerOptions": {
"types": ["@testing-library/jest-dom", "node", "jest"],
"module": "commonjs",
"target": "es6",
"outDir": "./dist",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"jsx": "react",
"lib": ["es2019", "dom"]
},
"include": ["./src/**/**.*", "src/*.ts", "src/setupTests.tsx"]
"exclude": ["node_modules"]
}
Step 4: Configure Jest
Replace the content of your jest.config.js file with the following:
module.exports = {
testEnvironment: "jest-environment-jsdom",
setupFilesAfterEnv: ["<rootDir>/src/setupTests.tsx"], // Update the path if your setupTests file is located elsewhere
transform: {
"^.+\\.tsx?$": "babel-jest", // Or ts-jest if you're using ts-jest
},
moduleFileExtensions: ["ts", "tsx", "js", "jsx"],
};
Next, create a setupTests.tsx file in your src folder and add the following:
import "@testing-library/jest-dom";
Step 5: Write Test Cases
Create a test file, e.g., YourComponent.test.tsx, in your project’s tests folder. This is where you’ll write your unit test cases.
Step 6: Run Tests
Run the following command to execute your tests:
npm test
Notes
- If you encounter an error related to
@testing-library/jest-dom, importing it in your test files usually resolves the issue. - Remember, this guide focuses on setting up the environment; you’ll need to figure out how to write the actual test cases based on your application.
I hope this guide saves you the frustration I faced. Happy testing! 🚀
SOCIAL SHARE CARD GENERATOR