jest-testing-patterns
Use when jest testing patterns including unit tests, mocks, spies, snapshots, and assertion techniques for comprehensive test coverage.
What this skill does
# Jest Testing Patterns
Master Jest testing patterns including unit tests, mocks, spies, snapshots, and assertion techniques for comprehensive test coverage. This skill covers the fundamental patterns and practices for writing effective, maintainable tests using Jest.
## Basic Test Structure
### Test Suite Organization
```javascript
describe('Calculator', () => {
describe('add', () => {
it('should add two positive numbers', () => {
expect(add(2, 3)).toBe(5);
});
it('should add negative numbers', () => {
expect(add(-2, -3)).toBe(-5);
});
it('should handle zero', () => {
expect(add(0, 5)).toBe(5);
});
});
describe('subtract', () => {
it('should subtract two numbers', () => {
expect(subtract(5, 3)).toBe(2);
});
});
});
```
### Setup and Teardown
```javascript
describe('Database operations', () => {
let db;
// Runs once before all tests in this describe block
beforeAll(async () => {
db = await initializeDatabase();
});
// Runs once after all tests in this describe block
afterAll(async () => {
await db.close();
});
// Runs before each test
beforeEach(() => {
db.clear();
});
// Runs after each test
afterEach(() => {
db.resetMocks();
});
it('should insert a record', async () => {
const result = await db.insert({ name: 'John' });
expect(result.id).toBeDefined();
});
it('should find a record', async () => {
await db.insert({ id: 1, name: 'John' });
const result = await db.findById(1);
expect(result.name).toBe('John');
});
});
```
## Matchers and Assertions
### Common Matchers
```javascript
describe('Matchers', () => {
it('should test equality', () => {
expect(2 + 2).toBe(4); // Strict equality
expect({ a: 1 }).toEqual({ a: 1 }); // Deep equality
expect([1, 2, 3]).toStrictEqual([1, 2, 3]); // Strict deep equality
});
it('should test truthiness', () => {
expect(true).toBeTruthy();
expect(false).toBeFalsy();
expect(null).toBeNull();
expect(undefined).toBeUndefined();
expect('value').toBeDefined();
});
it('should test numbers', () => {
expect(4).toBeGreaterThan(3);
expect(4).toBeGreaterThanOrEqual(4);
expect(3).toBeLessThan(4);
expect(3).toBeLessThanOrEqual(3);
expect(0.1 + 0.2).toBeCloseTo(0.3, 5);
});
it('should test strings', () => {
expect('team').not.toMatch(/I/);
expect('Christoph').toMatch(/stop/);
expect('hello world').toContain('world');
});
it('should test arrays and iterables', () => {
const list = ['apple', 'banana', 'cherry'];
expect(list).toContain('banana');
expect(list).toHaveLength(3);
expect(new Set(list)).toContain('apple');
});
it('should test objects', () => {
expect({ a: 1, b: 2 }).toHaveProperty('a');
expect({ a: 1, b: 2 }).toHaveProperty('a', 1);
expect({ a: { b: { c: 1 } } }).toHaveProperty('a.b.c', 1);
});
it('should test exceptions', () => {
expect(() => {
throw new Error('error');
}).toThrow();
expect(() => {
throw new Error('Invalid input');
}).toThrow('Invalid input');
expect(() => {
throw new Error('Invalid input');
}).toThrow(/Invalid/);
});
});
```
### Async Assertions
```javascript
describe('Async tests', () => {
// Using async/await
it('should fetch data', async () => {
const data = await fetchData();
expect(data).toBeDefined();
});
// Using promises
it('should fetch data with promise', () => {
return fetchData().then(data => {
expect(data).toBeDefined();
});
});
// Testing promise rejection
it('should handle errors', async () => {
await expect(fetchInvalidData()).rejects.toThrow('Not found');
});
// Using resolves/rejects
it('should resolve with data', async () => {
await expect(fetchData()).resolves.toEqual({ id: 1 });
});
it('should reject with error', async () => {
await expect(fetchInvalidData()).rejects.toThrow();
});
});
```
## Mocking
### Function Mocks
```javascript
describe('Function mocking', () => {
it('should mock a function', () => {
const mockFn = jest.fn();
mockFn('arg1', 'arg2');
expect(mockFn).toHaveBeenCalled();
expect(mockFn).toHaveBeenCalledWith('arg1', 'arg2');
expect(mockFn).toHaveBeenCalledTimes(1);
});
it('should mock return values', () => {
const mockFn = jest.fn()
.mockReturnValue(42)
.mockReturnValueOnce(1)
.mockReturnValueOnce(2);
expect(mockFn()).toBe(1);
expect(mockFn()).toBe(2);
expect(mockFn()).toBe(42);
});
it('should mock async functions', async () => {
const mockFn = jest.fn()
.mockResolvedValue('success')
.mockResolvedValueOnce('first call');
expect(await mockFn()).toBe('first call');
expect(await mockFn()).toBe('success');
});
it('should mock implementations', () => {
const mockFn = jest.fn((a, b) => a + b);
expect(mockFn(1, 2)).toBe(3);
mockFn.mockImplementation((a, b) => a * b);
expect(mockFn(2, 3)).toBe(6);
});
});
```
### Module Mocking
```javascript
// __mocks__/axios.js
export default {
get: jest.fn(() => Promise.resolve({ data: {} })),
post: jest.fn(() => Promise.resolve({ data: {} }))
};
// userService.test.js
import axios from 'axios';
import { getUser, createUser } from './userService';
jest.mock('axios');
describe('UserService', () => {
afterEach(() => {
jest.clearAllMocks();
});
it('should get user', async () => {
const mockUser = { id: 1, name: 'John' };
axios.get.mockResolvedValue({ data: mockUser });
const user = await getUser(1);
expect(axios.get).toHaveBeenCalledWith('/users/1');
expect(user).toEqual(mockUser);
});
it('should create user', async () => {
const newUser = { name: 'Jane' };
const createdUser = { id: 2, name: 'Jane' };
axios.post.mockResolvedValue({ data: createdUser });
const user = await createUser(newUser);
expect(axios.post).toHaveBeenCalledWith('/users', newUser);
expect(user).toEqual(createdUser);
});
});
```
### Partial Mocking
```javascript
// utils.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
export const multiply = (a, b) => a * b;
// calculator.test.js
import * as utils from './utils';
jest.mock('./utils', () => ({
...jest.requireActual('./utils'),
multiply: jest.fn()
}));
describe('Calculator', () => {
it('should use real add function', () => {
expect(utils.add(2, 3)).toBe(5);
});
it('should use mocked multiply function', () => {
utils.multiply.mockReturnValue(10);
expect(utils.multiply(2, 3)).toBe(10);
expect(utils.multiply).toHaveBeenCalledWith(2, 3);
});
});
```
## Spies
### Spying on Methods
```javascript
describe('Spies', () => {
it('should spy on object methods', () => {
const calculator = {
add: (a, b) => a + b
};
const spy = jest.spyOn(calculator, 'add');
calculator.add(2, 3);
expect(spy).toHaveBeenCalled();
expect(spy).toHaveBeenCalledWith(2, 3);
expect(spy).toHaveReturnedWith(5);
spy.mockRestore();
});
it('should spy and mock implementation', () => {
const logger = {
log: (message) => console.log(message)
};
const spy = jest.spyOn(logger, 'log').mockImplementation(() => {});
logger.log('test');
expect(spy).toHaveBeenCalledWith('test');
spy.mockRestore();
});
it('should spy on getter', () => {
const obj = {
get value() {
return 42;
}
};
const spy = jest.spyOn(obj, 'value', 'get').mockReturnValue(100);
expect(obj.value).toBe(100);
spy.mockRestore();
});
});
```
### Spying on Global Functions
```javascript
describe('Global spies', () => {
it('should spy on console.log', () => {
const spy = jest.spyOn(console, 'log').mockImplementation();
console.log('test message');
expect(spy).toHaveBeenCalledWith('test message');
spy.mockRestore();
});
it('shouldRelated in Code Review
gstack
IncludedFast headless browser for QA testing and site dogfooding. Navigate pages, interact with elements, verify state, diff before/after, take annotated screenshots, test responsive layouts, forms, uploads, dialogs, and capture bug evidence. Use when asked to open or test a site, verify a deployment, dogfood a user flow, or file a bug with screenshots. (gstack)
startup-due-diligence
IncludedLegal due diligence review for seed-stage and Series A startups (US, Delaware C-Corp focus). Supports both investor and founder perspectives. Capabilities include: (1) Interactive document review and issue spotting; (2) Document request list generation; (3) Cap table and SAFE/convertible note analysis; (4) Red flag identification with severity ratings; (5) Diligence report generation. TRIGGERS: due diligence, DD, startup investment, cap table review, Series A, seed round, investor diligence, legal review startup, SAFE analysis, convertible note, 409A, founder vesting.
interview-master
IncludedThis skill should be used when the user asks to "generate interview questions", "prepare for interview", "optimize resume", "conduct mock interview", "analyze git commits for resume", "generate resume from code", "review my resume", or mentions interview preparation, career assistance, or extracting project experience from git history. Provides comprehensive interview and career development guidance for both job seekers and interviewers.
fix-issue
IncludedFixes GitHub issues using parallel analysis agents for root cause investigation, code exploration, and regression detection. Reads issue context from gh CLI, searches codebase and memory for related patterns, generates a fix with tests, and links the resolution back to the issue via PR. Includes prevention analysis to avoid recurrence. Use when debugging errors, resolving regressions, fixing bugs, or triaging issues.
sf-apex
IncludedGenerates and reviews Salesforce Apex code with 150-point scoring. TRIGGER when: user writes, reviews, or fixes Apex classes, triggers, test classes, batch/queueable/schedulable jobs, or touches .cls/.trigger files. DO NOT TRIGGER when: LWC JavaScript (use sf-lwc), Flow XML (use sf-flow), SOQL-only queries (use sf-soql), or non-Salesforce code.
swift-development
IncludedComprehensive Swift development for building, testing, and deploying iOS/macOS applications. Use when Claude needs to: (1) Build Swift packages or Xcode projects from command line, (2) Run tests with XCTest or Swift Testing framework, (3) Manage iOS simulators with simctl, (4) Handle code signing, provisioning profiles, and app distribution, (5) Format or lint Swift code with SwiftFormat/SwiftLint, (6) Work with Swift Package Manager (SPM), (7) Implement Swift 6 concurrency patterns (async/await, actors, Sendable), (8) Create SwiftUI views with MVVM architecture, (9) Set up Core Data or SwiftData persistence, or any other Swift/iOS/macOS development tasks.