jest
Jest Testing Framework
Overview
Jest is a delightful JavaScript testing framework with a focus on simplicity. It works with projects using Babel, TypeScript, Node, React, Angular, Vue, and more.
Quick Start
Installation:
npm install --save-dev jest
Add to package.json:
{
"scripts": {
"test": "jest"
}
}
First test (sum.test.js):
const sum = require('./sum');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
Run tests:
npm test
Basic Test Structure
Test Blocks
test(name, fn)- Single testdescribe(name, fn)- Groups related testsonly- Run only this test:test.only(),describe.only()skip- Skip this test:test.skip(),describe.skip()
describe('Math operations', () => {
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
test('multiplies 3 * 4 to equal 12', () => {
expect(multiply(3, 4)).toBe(12);
});
});
Common Matchers
Exact Equality
// Primitive values
expect(2 + 2).toBe(4);
// Objects and arrays (deep equality)
expect({ one: 1, two: 2 }).toEqual({ one: 1, two: 2 });
Truthiness
toBeNull() // matches only null
toBeUndefined() // matches only undefined
toBeDefined() // opposite of toBeUndefined
toBeTruthy() // matches if statement truthy
toBeFalsy() // matches if statement falsy
Numbers
toBeGreaterThan(3)
toBeGreaterThanOrEqual(3.5)
toBeLessThan(5)
toBeLessThanOrEqual(4.5)
toBeCloseTo(0.3) // floating point
Strings
toMatch(/stop/)
Arrays
toContain('milk')
Negation
expect(2 + 2).not.toBe(5);
Testing Async Code
Promises
// Return the promise
test('the data is peanut butter', () => {
return fetchData().then(data => {
expect(data).toBe('peanut butter');
});
});
// Use .resolves
test('the data is peanut butter', () => {
return expect(fetchData()).resolves.toBe('peanut butter');
});
// Use .rejects
test('the fetch fails', () => {
return expect(fetchData()).rejects.toMatch('error');
});
Async/Await
test('the data is peanut butter', async () => {
const data = await fetchData();
expect(data).toBe('peanut butter');
});
test('the fetch fails', async () => {
await expect(fetchData()).rejects.toMatch('error');
});
Callbacks
test('the data is peanut butter', done => {
function callback(data) {
expect(data).toBe('peanut butter');
done();
}
fetchDataCallback(callback);
});
Setup and Teardown
Repeating Setup (Each Test)
beforeEach(() => {
initializeCityDatabase();
});
afterEach(() => {
clearCityDatabase();
});
One-Time Setup
beforeAll(() => {
return initializeCityDatabase();
});
afterAll(() => {
return clearCityDatabase();
});
Scoping
Hooks in describe blocks apply only to tests within that block. Outer hooks run before inner hooks.
describe('outer', () => {
beforeAll(() => { /* runs first */ });
beforeEach(() => { /* runs before each test */ });
describe('inner', () => {
beforeAll(() => { /* runs second */ });
beforeEach(() => { /* runs before each test in inner */ });
});
});
Mocking
Mock Functions
const mockFn = jest.fn(x => 42 + x);
// Inspect calls
expect(mockFn.mock.calls.length).toBe(2);
expect(mockFn.mock.calls[0][0]).toBe(0);
// Return values
mockFn.mockReturnValueOnce(10).mockReturnValue(true);
// Implementation
mockFn.mockImplementation(() => 'default');
Module Mocking
import axios from 'axios';
jest.mock('axios');
// Mock resolved value
axios.get.mockResolvedValue({ data: users });
// Mock implementation
axios.get.mockImplementation(() => Promise.resolve(resp));
Mock Matchers
expect(mockFunc).toHaveBeenCalled();
expect(mockFunc).toHaveBeenCalledWith(arg1, arg2);
expect(mockFunc).toHaveBeenLastCalledWith(arg1, arg2);
Snapshot Testing
Basic Snapshot
test('renders correctly', () => {
const tree = renderer.create(<Link />).toJSON();
expect(tree).toMatchSnapshot();
});
Update Snapshots
jest --updateSnapshot
# or
jest -u
Inline Snapshots
test('renders correctly', () => {
const tree = renderer.create(<Link />).toJSON();
expect(tree).toMatchInlineSnapshot();
});
Property Matchers
expect(user).toMatchSnapshot({
createdAt: expect.any(Date),
id: expect.any(Number),
});
Configuration
Generate Config
npm init jest@latest
Config File (jest.config.js)
module.exports = {
// Test environment
testEnvironment: 'node', // or 'jsdom' for React
// Test file patterns
testMatch: [
'**/__tests__/**/*.[jt]s?(x)',
'**/?(*.)+(spec|test).[jt]s?(x)'
],
// Coverage
collectCoverageFrom: ['src/**/*.{js,jsx}'],
coverageDirectory: 'coverage',
// Setup files
setupFilesAfterEnv: ['<rootDir>/src/setupTests.js'],
// Transforms (Babel, TypeScript)
transform: {
'^.+\\.(js|jsx)$': 'babel-jest',
},
// Module mocking
moduleNameMapper: {
'\\.(css|less)$': 'identity-obj-proxy',
},
};
TypeScript
npm install --save-dev ts-jest @types/jest
// jest.config.js
module.exports = {
preset: 'ts-jest',
};
React
npm install --save-dev @testing-library/react @testing-library/jest-dom jest-environment-jsdom
// jest.config.js
module.exports = {
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['<rootDir>/src/setupTests.js'],
};
// src/setupTests.js
import '@testing-library/jest-dom';
CLI Options
jest # Run all tests
jest --watch # Watch mode
jest --coverage # Generate coverage
jest --updateSnapshot # Update snapshots
jest --verbose # Detailed output
jest --findRelatedTests # Test changed files
Framework-Specific Testing
React (see TutorialReact.md)
import { render, screen } from '@testing-library/react';
test('renders button', () => {
render(<Button>Click me</Button>);
expect(screen.getByText('Click me')).toBeInTheDocument();
});
React Native (see TutorialReactNative.md)
Use react-test-renderer for snapshot testing.
Async Patterns (see TutorialAsync.md)
Comprehensive examples for promises, async/await, callbacks, and timers.
Best Practices
- Descriptive test names - "should return user when id exists" vs "returns user"
- One assertion per test - Keep tests focused
- Arrange-Act-Assert - Structure tests clearly
- Mock external dependencies - Don't make real API calls
- Test behavior, not implementation - Focus on what, not how
- Use setup/teardown - Avoid code duplication
- Keep tests deterministic - No random data or dates (mock them)
Resources
Setup & Configuration
- GettingStarted.md - Installation, Babel, TypeScript, ESLint setup
- Configuration.md - Complete config options reference
- CLI.md - All command-line options
- EnvironmentVariables.md - Environment setup
- TestingFrameworks.md - Framework-specific setup guides
Core Testing
- UsingMatchers.md - Common matchers (toBe, toEqual, truthiness, numbers, arrays)
- TestingAsyncCode.md - Promises, async/await, callbacks, timers
- SetupAndTeardown.md - beforeEach, afterEach, beforeAll, afterAll, scoping
Mocking
- MockFunctions.md - Mock functions, .mock property, return values
- MockFunctionAPI.md - Complete mock API reference
- ManualMocks.md - Manual module mocks
- Es6ClassMocks.md - ES6 class mocking
- BypassingModuleMocks.md - Bypassing module mocks
API References
- ExpectAPI.md - Complete expect() matcher reference (63k+ bytes)
- GlobalAPI.md - describe, test, it, skip, only, etc. (35k+ bytes)
- JestObjectAPI.md - Jest object API (36k+ bytes)
Advanced Features
- SnapshotTesting.md - Snapshot testing, inline snapshots, property matchers
- TimerMocks.md - Fake timers, timer mocking APIs
- CodeTransformation.md - Custom transforms
- ECMAScriptModules.md - ESM support
- WatchPlugins.md - Custom watch plugins
Framework Tutorials
- TutorialReact.md - React testing with @testing-library/react
- TutorialReactNative.md - React Native testing
- TutorialAsync.md - Async patterns and examples
- TutorialjQuery.md - jQuery testing
Integration Guides
- Webpack.md - Webpack integration
- Puppeteer.md - Puppeteer integration
- DynamoDB.md - DynamoDB testing
- MongoDB.md - MongoDB testing
Meta & Support
- Architecture.md - Jest architecture
- Troubleshooting.md - Common issues and solutions
- MigrationGuide.md - Upgrading guide
- JestPlatform.md - Jest platform packages
- JestCommunity.md - Community resources
- MoreResources.md - Additional learning resources
Assets
- assets/configs/ - Configuration templates (basic, TypeScript, Babel, React, package.json)
- assets/test-templates/ - Test file templates (basic, async, mock, snapshot, setup, react)
More from ghosttypes/ff-5mp-api-ts
typescript-best-practices
TypeScript best practices and patterns for writing type-safe, maintainable code. Use when working with TypeScript files, configuring tsconfig, defining interfaces/types, implementing error handling, writing generics, or setting up type-safe communication patterns. Includes patterns for discriminated unions, type guards, utility types, and more.
34npm-to-pnpm
Migrate projects from npm to pnpm including lockfile conversion, workspace setup, CI/CD updates, and troubleshooting. Use when converting a single package from npm to pnpm, migrating npm workspaces or monorepos, updating CI/CD pipelines for pnpm, troubleshooting issues after npm to pnpm migration, or converting package-lock.json to pnpm-lock.yaml.
17sub-agent-creator
Interactive sub-agent creation skill for Claude Code. Use when user wants to create a custom subagent or mentions needing a specialized agent for specific tasks. This skill guides the entire subagent creation process including identifier design, system prompt generation, skill/context selection, and writing properly formatted agent files to .claude/agents.
12biome
Comprehensive Biome (biomejs.dev) integration for professional TypeScript/JavaScript development. Use for linting, formatting, code quality, and flawless Biome integration into codebases. Covers installation, configuration, migration from ESLint/Prettier, all linter rules, formatter options, CLI usage, editor integration, monorepo setup, and CI/CD integration. Use when working with Biome tooling, configuring biome.json, setting up linting/formatting, migrating projects, debugging Biome issues, or implementing production-ready Biome workflows.
11eslint
Professional-grade ESLint development for JavaScript and TypeScript projects. Use when working with ESLint for (1) configuring ESLint in projects, (2) understanding or fixing ESLint errors and warnings, (3) creating or modifying ESLint rules, (4) integrating ESLint into build systems or editors, (5) migrating ESLint configurations, (6) setting up custom parsers or plugins, (7) troubleshooting ESLint issues, (8) implementing code quality standards, or (9) any task involving ESLint setup, configuration, or usage. Covers all ESLint versions with focus on v9+ flat config format.
10vitest
Comprehensive Vitest testing framework skill for writing, configuring, and running tests in JavaScript/TypeScript projects. Use when Claude needs to: set up Vitest in a new or existing project (Vite or non-Vite), write or modify tests using Vitest APIs, configure Vitest for specific scenarios (coverage, browser testing, mocking, etc.), migrate from Jest or older Vitest versions, debug test failures or configuration issues, implement advanced testing patterns (workspace, browser mode, snapshots, mocking).
10