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 enviro
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", "jest4category: AI & Agents5source: antigravity6tags: [javascript, typescript, react, node, api, ai, agent, template, security, rag]7url: https://github.com/sickn33/antigravity-awesome-skills/tree/main/skills/jest-skill8metadata:9 source: https://skillmd.com/skills/sickn33/jest-skill10---111213# Jest Testing Skill14## When to Use1516Use 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",...171819## Core Patterns2021### Basic Test2223```javascript24describe('Calculator', () => {25 let calc;26 beforeEach(() => { calc = new Calculator(); });2728 test('adds two numbers', () => {29 expect(calc.add(2, 3)).toBe(5);30 });3132 test('throws on division by zero', () => {33 expect(() => calc.divide(10, 0)).toThrow('Division by zero');34 });35});36```3738### Matchers3940```javascript41expect(value).toBe(exact); // === strict42expect(value).toEqual(object); // deep equality43expect(value).toBeTruthy();44expect(value).toBeNull();45expect(value).toBeGreaterThan(3);46expect(value).toBeCloseTo(0.3, 5);47expect(str).toMatch(/regex/);48expect(arr).toContain(item);49expect(arr).toHaveLength(3);50expect(obj).toHaveProperty('name');51expect(obj).toMatchObject({ name: 'Alice' });52expect(() => fn()).toThrow(CustomError);53```5455### Mocking5657```javascript58// Mock function59const mockFn = jest.fn();60mockFn.mockReturnValue(42);61mockFn.mockResolvedValue({ data: 'test' });62expect(mockFn).toHaveBeenCalledWith('arg1');63expect(mockFn).toHaveBeenCalledTimes(1);6465// Mock module66jest.mock('./database');67const db = require('./database');68db.getUser.mockResolvedValue({ name: 'Alice' });6970// Mock with implementation71jest.mock('./api', () => ({72 fetchUsers: jest.fn().mockResolvedValue([{ name: 'Alice' }]),73}));7475// Spy76const spy = jest.spyOn(console, 'log').mockImplementation();77expect(spy).toHaveBeenCalledWith('expected');78spy.mockRestore();7980// Fake timers81jest.useFakeTimers();82jest.advanceTimersByTime(1000);83jest.useRealTimers();84```8586### Async Testing8788```javascript89test('fetches users', async () => {90 const users = await fetchUsers();91 expect(users).toHaveLength(3);92});9394test('resolves with data', () => {95 return expect(fetchData()).resolves.toEqual({ data: 'value' });96});9798test('rejects with error', () => {99 return expect(fetchBadData()).rejects.toThrow('not found');100});101```102103### React Component Testing (Testing Library)104105```javascript106import { render, screen, fireEvent, waitFor } from '@testing-library/react';107import '@testing-library/jest-dom';108import LoginForm from './LoginForm';109110test('submits login form', async () => {111 const onSubmit = jest.fn();112 render(<LoginForm onSubmit={onSubmit} />);113114 fireEvent.change(screen.getByLabelText('Email'), {115 target: { value: 'user@test.com' },116 });117 fireEvent.change(screen.getByLabelText('Password'), {118 target: { value: 'password123' },119 });120 fireEvent.click(screen.getByRole('button', { name: /login/i }));121122 await waitFor(() => {123 expect(onSubmit).toHaveBeenCalledWith({124 email: 'user@test.com', password: 'password123',125 });126 });127});128```129130### Snapshot Testing131132```javascript133test('renders correctly', () => {134 const tree = renderer.create(<Button label="Click" />).toJSON();135 expect(tree).toMatchSnapshot();136});137// Update: jest --updateSnapshot138```139140### Anti-Patterns141142| Bad | Good | Why |143|-----|------|-----|144| `expect(x === y).toBe(true)` | `expect(x).toBe(y)` | Better errors |145| No `await` on async | Always `await` | Swallows failures |146| Snapshot everything | Snapshot UI, assert logic | Snapshot fatigue |147148## Quick Reference149150| Task | Command |151|------|---------|152| Run all | `npx jest` |153| Watch | `npx jest --watch` |154| Coverage | `npx jest --coverage` |155| Update snapshots | `npx jest --updateSnapshot` |156| Run file | `npx jest tests/calc.test.js` |157| Single test | `test.only('name', () => {})` |158159## Deep Patterns160161For production-grade patterns, see `reference/playbook.md`:162163| Section | What's Inside |164|---------|--------------|165| §1 Production Config | Node + React configs, path aliases, coverage thresholds |166| §2 Mocking Deep Dive | Module/partial/manual mocks, spies, timers, env vars |167| §3 Async Patterns | Promises, rejections, event emitters, streams |168| §4 test.each | Array, tagged template, describe.each for table-driven tests |169| §5 Custom Matchers | toBeWithinRange, toBeValidEmail, TypeScript declarations |170| §6 React Testing Library | userEvent, hooks, context providers |171| §7 Snapshot Testing | Component, inline, property matchers |172| §8 API Service Testing | Mocked axios, CRUD patterns, error handling |173| §9 Global Setup | Multi-project config, DB setup/teardown |174| §10 CI/CD | GitHub Actions with coverage gates |175| §11 Debugging Table | 10 common problems with fixes |176| §12 Best Practices | 15-item production checklist |177178## Limitations179180- Use this skill only when the task clearly matches its upstream source and local project context.181- Verify commands, generated code, dependencies, credentials, and external service behavior before applying changes.182- Do not treat examples as a substitute for enviro