Jest Testing Skill
When to Use
Use this skill when you need generates Jest unit and integration tests in JavaScript or TypeScript. Covers mocking, snapshots, async testing, and React component testing. Use when user mentions "Jest", "describe/it/expect", "jest.mock", "toMatchSnapshot". Triggers on: "Jest", "expect().toBe()", "jest.mock",...
Core Patterns
Basic Test
describe('Calculator', () => {
let calc;
beforeEach(() => { calc = new Calculator(); });
test('adds two numbers', () => {
expect(calc.add(2, 3)).toBe(5);
});
test('throws on division by zero', () => {
expect(() => calc.divide(10, 0)).toThrow('Division by zero');
});
});
Matchers
expect(value).toBe(exact); // === strict
expect(value).toEqual(object); // deep equality
expect(value).toBeTruthy();
expect(value).toBeNull();
expect(value).toBeGreaterThan(3);
expect(value).toBeCloseTo(0.3, 5);
expect(str).toMatch(/regex/);
expect(arr).toContain(item);
expect(arr).toHaveLength(3);
expect(obj).toHaveProperty('name');
expect(obj).toMatchObject({ name: 'Alice' });
expect(() => fn()).toThrow(CustomError);
Mocking
// Mock function
const mockFn = jest.fn();
mockFn.mockReturnValue(42);
mockFn.mockResolvedValue({ data: 'test' });
expect(mockFn).toHaveBeenCalledWith('arg1');
expect(mockFn).toHaveBeenCalledTimes(1);
// Mock module
jest.mock('./database');
const db = require('./database');
db.getUser.mockResolvedValue({ name: 'Alice' });
// Mock with implementation
jest.mock('./api', () => ({
fetchUsers: jest.fn().mockResolvedValue([{ name: 'Alice' }]),
}));
// Spy
const spy = jest.spyOn(console, 'log').mockImplementation();
expect(spy).toHaveBeenCalledWith('expected');
spy.mockRestore();
// Fake timers
jest.useFakeTimers();
jest.advanceTimersByTime(1000);
jest.useRealTimers();
Async Testing
test('fetches users', async () => {
const users = await fetchUsers();
expect(users).toHaveLength(3);
});
test('resolves with data', () => {
return expect(fetchData()).resolves.toEqual({ data: 'value' });
});
test('rejects with error', () => {
return expect(fetchBadData()).rejects.toThrow('not found');
});
React Component Testing (Testing Library)
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import '@testing-library/jest-dom';
import LoginForm from './LoginForm';
test('submits login form', async () => {
const
render(<LoginForm />);
fireEvent.change(screen.getByLabelText('Email'), {
target: { value: 'user@test.com' },
});
fireEvent.change(screen.getByLabelText('Password'), {
target: { value: 'password123' },
});
fireEvent.click(screen.getByRole('button', { name: /login/i }));
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledWith({
email: 'user@test.com', password: 'password123',
});
});
});
Snapshot Testing
test('renders correctly', () => {
const tree = renderer.create(<Button label="Click" />).toJSON();
expect(tree).toMatchSnapshot();
});
// Update: jest --updateSnapshot
Anti-Patterns
| Bad |
Good |
Why |
expect(x === y).toBe(true) |
expect(x).toBe(y) |
Better errors |
No await on async |
Always await |
Swallows failures |
| Snapshot everything |
Snapshot UI, assert logic |
Snapshot fatigue |
Quick Reference
| Task |
Command |
| Run all |
npx jest |
| Watch |
npx jest --watch |
| Coverage |
npx jest --coverage |
| Update snapshots |
npx jest --updateSnapshot |
| Run file |
npx jest tests/calc.test.js |
| Single test |
test.only('name', () => {}) |
Deep Patterns
For production-grade patterns, see reference/playbook.md:
| Section |
What's Inside |
| §1 Production Config |
Node + React configs, path aliases, coverage thresholds |
| §2 Mocking Deep Dive |
Module/partial/manual mocks, spies, timers, env vars |
| §3 Async Patterns |
Promises, rejections, event emitters, streams |
| §4 test.each |
Array, tagged template, describe.each for table-driven tests |
| §5 Custom Matchers |
toBeWithinRange, toBeValidEmail, TypeScript declarations |
| §6 React Testing Library |
userEvent, hooks, context providers |
| §7 Snapshot Testing |
Component, inline, property matchers |
| §8 API Service Testing |
Mocked axios, CRUD patterns, error handling |
| §9 Global Setup |
Multi-project config, DB setup/teardown |
| §10 CI/CD |
GitHub Actions with coverage gates |
| §11 Debugging Table |
10 common problems with fixes |
| §12 Best Practices |
15-item production checklist |
Limitations
- Use this skill only when the task clearly matches its upstream source and local project context.
- Verify commands, generated code, dependencies, credentials, and external service behavior before applying changes.
- Do not treat examples as a substitute for environment-specific tests, security review, or user approval for destructive or costly actions.
1---2name: jest-skill3description: "Generates Jest unit and integration tests in JavaScript or TypeScript. Covers mocking, snapshots, async testing, and React component testing. Use when user mentions \"Jest\", \"describe/it/expect\", \"jest.mock\", \"toMatchSnapshot\"."4risk: critical5source: https://github.com/LambdaTest/agent-skills/tree/main/jest-skill6source_repo: LambdaTest/agent-skills7source_type: community8date_added: 2026-07-019license: MIT10license_source: https://github.com/LambdaTest/agent-skills/blob/main/LICENSE11metadata:12 source: https://skillmd.com/skills/lambdatest/jest-skill13---1415# Jest Testing Skill16## When to Use1718Use this skill when you need generates Jest unit and integration tests in JavaScript or TypeScript. Covers mocking, snapshots, async testing, and React component testing. Use when user mentions "Jest", "describe/it/expect", "jest.mock", "toMatchSnapshot". Triggers on: "Jest", "expect().toBe()", "jest.mock",...192021## Core Patterns2223### Basic Test2425```javascript26describe('Calculator', () => {27 let calc;28 beforeEach(() => { calc = new Calculator(); });2930 test('adds two numbers', () => {31 expect(calc.add(2, 3)).toBe(5);32 });3334 test('throws on division by zero', () => {35 expect(() => calc.divide(10, 0)).toThrow('Division by zero');36 });37});38```3940### Matchers4142```javascript43expect(value).toBe(exact); // === strict44expect(value).toEqual(object); // deep equality45expect(value).toBeTruthy();46expect(value).toBeNull();47expect(value).toBeGreaterThan(3);48expect(value).toBeCloseTo(0.3, 5);49expect(str).toMatch(/regex/);50expect(arr).toContain(item);51expect(arr).toHaveLength(3);52expect(obj).toHaveProperty('name');53expect(obj).toMatchObject({ name: 'Alice' });54expect(() => fn()).toThrow(CustomError);55```5657### Mocking5859```javascript60// Mock function61const mockFn = jest.fn();62mockFn.mockReturnValue(42);63mockFn.mockResolvedValue({ data: 'test' });64expect(mockFn).toHaveBeenCalledWith('arg1');65expect(mockFn).toHaveBeenCalledTimes(1);6667// Mock module68jest.mock('./database');69const db = require('./database');70db.getUser.mockResolvedValue({ name: 'Alice' });7172// Mock with implementation73jest.mock('./api', () => ({74 fetchUsers: jest.fn().mockResolvedValue([{ name: 'Alice' }]),75}));7677// Spy78const spy = jest.spyOn(console, 'log').mockImplementation();79expect(spy).toHaveBeenCalledWith('expected');80spy.mockRestore();8182// Fake timers83jest.useFakeTimers();84jest.advanceTimersByTime(1000);85jest.useRealTimers();86```8788### Async Testing8990```javascript91test('fetches users', async () => {92 const users = await fetchUsers();93 expect(users).toHaveLength(3);94});9596test('resolves with data', () => {97 return expect(fetchData()).resolves.toEqual({ data: 'value' });98});99100test('rejects with error', () => {101 return expect(fetchBadData()).rejects.toThrow('not found');102});103```104105### React Component Testing (Testing Library)106107```javascript108import { render, screen, fireEvent, waitFor } from '@testing-library/react';109import '@testing-library/jest-dom';110import LoginForm from './LoginForm';111112test('submits login form', async () => {113 const onSubmit = jest.fn();114 render(<LoginForm onSubmit={onSubmit} />);115116 fireEvent.change(screen.getByLabelText('Email'), {117 target: { value: 'user@test.com' },118 });119 fireEvent.change(screen.getByLabelText('Password'), {120 target: { value: 'password123' },121 });122 fireEvent.click(screen.getByRole('button', { name: /login/i }));123124 await waitFor(() => {125 expect(onSubmit).toHaveBeenCalledWith({126 email: 'user@test.com', password: 'password123',127 });128 });129});130```131132### Snapshot Testing133134```javascript135test('renders correctly', () => {136 const tree = renderer.create(<Button label="Click" />).toJSON();137 expect(tree).toMatchSnapshot();138});139// Update: jest --updateSnapshot140```141142### Anti-Patterns143144| Bad | Good | Why |145|-----|------|-----|146| `expect(x === y).toBe(true)` | `expect(x).toBe(y)` | Better errors |147| No `await` on async | Always `await` | Swallows failures |148| Snapshot everything | Snapshot UI, assert logic | Snapshot fatigue |149150## Quick Reference151152| Task | Command |153|------|---------|154| Run all | `npx jest` |155| Watch | `npx jest --watch` |156| Coverage | `npx jest --coverage` |157| Update snapshots | `npx jest --updateSnapshot` |158| Run file | `npx jest tests/calc.test.js` |159| Single test | `test.only('name', () => {})` |160161## Deep Patterns162163For production-grade patterns, see `reference/playbook.md`:164165| Section | What's Inside |166|---------|--------------|167| §1 Production Config | Node + React configs, path aliases, coverage thresholds |168| §2 Mocking Deep Dive | Module/partial/manual mocks, spies, timers, env vars |169| §3 Async Patterns | Promises, rejections, event emitters, streams |170| §4 test.each | Array, tagged template, describe.each for table-driven tests |171| §5 Custom Matchers | toBeWithinRange, toBeValidEmail, TypeScript declarations |172| §6 React Testing Library | userEvent, hooks, context providers |173| §7 Snapshot Testing | Component, inline, property matchers |174| §8 API Service Testing | Mocked axios, CRUD patterns, error handling |175| §9 Global Setup | Multi-project config, DB setup/teardown |176| §10 CI/CD | GitHub Actions with coverage gates |177| §11 Debugging Table | 10 common problems with fixes |178| §12 Best Practices | 15-item production checklist |179180## Limitations181182- Use this skill only when the task clearly matches its upstream source and local project context.183- Verify commands, generated code, dependencies, credentials, and external service behavior before applying changes.184- Do not treat examples as a substitute for environment-specific tests, security review, or user approval for destructive or costly actions.