Unit Testing with Jest: Writing Reliable JavaScript Tests
Jest is a delightful JavaScript testing framework with zero config. It handles assertions, mocking, and code coverage out of the box.
## Setup
```bash
npm install --save-dev jest
```
## Basic Test
```javascript
// sum.js
function sum(a, b) { return a + b; }
module.exports = sum;
// sum.test.js
const sum = require('./sum');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
```
## Matchers
```javascript
test('object assignment', () => {
const data = { one: 1 };
data['two'] = 2;
expect(data).toEqual({ one: 1, two: 2 });
});
test('null', () => {
const n = null;
expect(n).toBeNull();
expect(n).toBeDefined();
expect(n).not.toBeUndefined();
});
test('numbers', () => {
const val = 2 + 2;
expect(val).toBeGreaterThan(3);
expect(val).toBeLessThan(5);
});
```
## Testing Async Code
```javascript
test('fetches data', async () => {
const data = await fetchData();
expect(data).toEqual({ name: 'John' });
});
// Using resolves/rejects
expect(fetchData()).resolves.toEqual({ name: 'John' });
```
## Mocking
```javascript
test('mock function', () => {
const mockFn = jest.fn(x => x * 2);
mockFn(5);
expect(mockFn).toHaveBeenCalledWith(5);
expect(mockFn).toHaveReturnedWith(10);
});
```
## Setup/Teardown
```javascript
beforeEach(() => initDatabase());
afterEach(() => clearDatabase());
beforeAll(() => startServer());
afterAll(() => stopServer());
```
## Coverage
```bash
npx jest --coverage
```
## Conclusion
Tests catch bugs early and serve as documentation. Aim for high coverage on critical paths, not 100% on everything.
