Node.js Masterclass
High-Performance Backends01.Home02.Introduction03.Environment Setup04.Modules & Exports05.File System (fs)06.Path & OS Modules07.Buffer & Streams08.Events & EventEmitter09.HTTP Module10.NPM & Package.json11.Express.js Fundamentals12.Express Routing13.Express Middleware14.RESTful API Development15.Asynchronous Programming16.Error Handling17.Database with Mongoose18.Authentication with JWT19.Environment Variables20.Testing with Jest21.Deployment & PM2
Testing with Jest
Testing ensures your code works as expected and prevents bugs from reappearing (regressions).Jest is a delightful JavaScript Testing Framework with a focus on simplicity.
1. Getting Started
npm install jest --save-devAdd to package.json:
"scripts": {
"test": "jest"
}2. Writing Your First Test
Create a file named math.test.js. Jest will automatically find any file ending in .test.js or .spec.js.
const { add } = require('./math');
test('adds 1 + 2 to equal 3', () => {
expect(add(1, 2)).toBe(3);
});3. Testing Asynchronous Code
Jest makes testing async functions easy with async/await support.
test('fetches user data', async () => {
const user = await getUser(1);
expect(user.name).toBe('John');
});4. Mocking
Mocking allows you to isolate the code you're testing by replacing dependencies (like database calls) with fake implementations.
const axios = require('axios');
jest.mock('axios');
test('should fetch users', async () => {
const users = [{ name: 'Bob' }];
axios.get.mockResolvedValue({ data: users });
const result = await fetchUsers();
expect(result).toEqual(users);
});Goal: Aim for high "test coverage," but focus on testing the logic and edge cases that are most likely to break.