jest

Jest Testing Framework

Safety Notice

This listing is imported from skills.sh public index metadata. Review upstream SKILL.md and repository scripts before running.

Copy this and send it to your AI assistant to learn

Install skill "jest" with this command: npx skills add ghosttypes/ff-5mp-api-ts/ghosttypes-ff-5mp-api-ts-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 test

  • describe(name, fn)

  • Groups related tests

  • only

  • 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)

Source Transparency

This detail page is rendered from real SKILL.md content. Trust labels are metadata-based hints, not a safety guarantee.

Related Skills

Related by shared tags or category signals.

General

biome

No summary provided by upstream source.

Repository SourceNeeds Review
General

eslint

No summary provided by upstream source.

Repository SourceNeeds Review
General

vitest

No summary provided by upstream source.

Repository SourceNeeds Review
General

npm-to-pnpm

No summary provided by upstream source.

Repository SourceNeeds Review