𝗝𝗲𝘀𝘁 𝗧𝗲𝘀𝘁𝗶𝗻𝗴 𝗚𝘂𝗶𝗱𝗲 𝗳𝗼𝗿 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿𝘀
Testing helps you find bugs early. It improves code quality. It lets you ship features without breaking old code.
Jest is a popular testing tool for JavaScript and Node.js. Meta created it. It works with TypeScript, React, Next.js, and Express.js.
Why use Jest?
- It needs little setup.
- It runs tests in parallel for speed.
- It includes mocking tools.
- It shows code coverage reports.
- It provides clear error messages.
How to set up Jest:
- Create a Node.js project: npm init -y
- Install Jest: npm install --save-dev jest
- Update package.json scripts to include "test": "jest"
- Run tests with: npm test
Writing a simple test:
Create sum.js: function sum(a, b) { return a + b; } module.exports = sum;
Create sum.test.js: const sum = require("./sum"); test("adds two numbers", () => { expect(sum(2, 3)).toBe(5); });
Essential Jest tools:
- Assertions: Use expect() and toBe() to check values.
- Objects: Use toEqual() to compare objects or arrays.
- Organization: Use describe() to group related tests.
- Async: Jest handles async functions naturally using await.
- Mocks: Use jest.fn() to simulate functions. This keeps tests fast by avoiding real API calls or database hits.
- Hooks: Use beforeEach() and afterEach() to set up or clean up test data.
Measure your success:
Run npx jest --coverage to see your coverage report. This shows which parts of your code lack tests.
Testing APIs:
Use Supertest to test API endpoints. You can check status codes without starting a real server.
Snapshot Testing:
Use matchSnapshot() in React. This helps you find unexpected UI changes by comparing current renders to saved versions.
Best practices:
- Write tests that describe outcomes.
- Avoid testing internal code structure.
- Stay away from real databases in unit tests.
- Focus on meaningful coverage.
Mastering Jest helps you build reliable software.