Unit Testing with Jest
Write robust unit tests for your JavaScript applications using Jest framework.
# Unit Testing with Jest
Jest is the most popular testing framework for JavaScript. Let's learn how to write effective unit tests.
## Getting Started
Install Jest in your project:
```bash
npm install --save-dev jest
```
## Basic Test Structure
```javascript
describe('Calculator', () => {
test('adds two numbers', () => {
expect(add(2, 3)).toBe(5);
});
test('subtracts two numbers', () => {
expect(subtract(5, 3)).toBe(2);
});
});
```
## Common Matchers
```javascript
// Equality
expect(value).toBe(4);
expect(value).toEqual({ name: 'Alice' });
// Truthiness
expect(value).toBeTruthy();
expect(value).toBeFalsy();
expect(value).toBeNull();
// Numbers
expect(value).toBeGreaterThan(3);
expect(value).toBeLessThan(5);
// Strings
expect(string).toMatch(/pattern/);
// Arrays
expect(array).toContain('item');
```
## Testing Async Code
```javascript
test('fetches user data', async () => {
const data = await fetchUser(1);
expect(data.name).toBe('Alice');
});
```
## Mocking
```javascript
jest.mock('./api');
test('calls API correctly', () => {
const mockFetch = jest.fn();
api.fetch = mockFetch;
fetchData();
expect(mockFetch).toHaveBeenCalledWith('/users');
});
```
## Testing React Components
```javascript
import { render, screen } from '@testing-library/react';
test('renders button', () => {
render();
expect(screen.getByText('Click me')).toBeInTheDocument();
});
```
## Best Practices
1. Test behavior, not implementation
2. Keep tests simple and focused
3. Use descriptive test names
4. Avoid test interdependence
5. Mock external dependencies
Good tests give you confidence to refactor and add features. Write tests as you code!
You Might Also Like
React Hooks: A Complete Guide
Everything you need to know about React Hooks, from useState to custom hooks.
Read more →
Building RESTful APIs with Express.js
A comprehensive guide to creating scalable REST APIs using Express.js and Node.js.
Read more →
TypeScript Generics Tutorial
Write type-safe, reusable code with TypeScript generics and advanced type patterns.
Read more →