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-dev
Add 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.