xiaohongshu
xiaohongshu
jest
Write JavaScript/TypeScript tests with Jest including unit tests, mocking, snapshots, and coverage. Test React components, async code, and Node.js. Use for JavaScript testing, React testing, or test automation.
Full skill instructions
| Command | Purpose |
|---|---|
jest | Run all tests |
jest --watch | Watch mode |
jest --coverage | Generate coverage |
jest path/to/test | Run specific test |
jest -t "pattern" | Run matching tests |
# JavaScript
npm install --save-dev jest
# TypeScript
npm install --save-dev jest ts-jest @types/jest
npx ts-jest config:init
# React
npm install --save-dev @testing-library/react @testing-library/jest-dom
module.exports = {
// Test environment
testEnvironment: 'node', // or 'jsdom' for browser
// TypeScript
preset: 'ts-jest',
// Test file patterns
testMatch: ['**/__tests__/**/*.test.[jt]s?(x)'],
// Coverage
collectCoverageFrom: ['src/**/*.{js,ts,tsx}', '!src/**/*.d.ts'],
coverageThreshold: {
global: {
branches: 80,
functions: 80,
lines: 80,
statements: 80
}
},
// Module resolution
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1',
'\\.(css|less|scss)$': 'identity-obj-proxy'
},
// Setup files
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
// Transform
transform: {
'^.+\\.(ts|tsx)$': 'ts-jest'
}
};
import '@testing-library/jest-dom';
// Global mocks
global.fetch = jest.fn();
// Cleanup after each test
afterEach(() => {
jest.clearAllMocks();
});
describe('Calculator', () => {
// Setup before all tests
beforeAll(() => {
console.log('Starting Calculator tests');
});
// Setup before each test
beforeEach(() => {
// Reset state
});
// Cleanup after each test
afterEach(() => {
jest.clearAllMocks();
});
// Cleanup after all tests
afterAll(() => {
console.log('Finished Calculator tests');
});
describe('add', () => {
it('adds two positive numbers', () => {
expect(add(2, 3)).toBe(5);
});
it('adds negative numbers', () => {
expect(add(-1, -2)).toBe(-3);
});
it.each([
[1, 2, 3],
[0, 0, 0],
[-1, 1, 0]
])('adds %i + %i to equal %i', (a, b, expected) => {
expect(add(a, b)).toBe(expected);
});
});
// Skip test
it.skip('skipped test', () => {
// This test is skipped
});
// Only run this test
it.only('only this test runs', () => {
// Only this test runs in this file
});
});
// Equality
expect(value).toBe(expected); // Strict equality
expect(value).toEqual(expected); // Deep equality
expect(value).toStrictEqual(expected); // Strict deep equality
// Truthiness
expect(value).toBeTruthy();
expect(value).toBeFalsy();
expect(value).toBeNull();
expect(value).toBeUndefined();
expect(value).toBeDefined();
// Numbers
expect(value).toBeGreaterThan(3);
expect(value).toBeGreaterThanOrEqual(3);
expect(value).toBeLessThan(5);
expect(value).toBeCloseTo(0.3, 5); // Floating point
// Strings
expect(string).toMatch(/regex/);
expect(string).toContain('substring');
// Arrays
expect(array).toContain(item);
expect(array).toHaveLength(3);
expect(array).toContainEqual({ id: 1 }); // Deep equality
// Objects
expect(obj).toHaveProperty('key');
expect(obj).toHaveProperty('key', 'value');
expect(obj).toMatchObject({ subset: true });
// Exceptions
expect(() => throwError()).toThrow();
expect(() => throwError()).toThrow('error message');
expect(() => throwError()).toThrow(ErrorClass);
// Negation
expect(value).not.toBe(expected);
// Create mock function
const mockFn = jest.fn();
const mockFnWithReturn = jest.fn().mockReturnValue(42);
const mockFnWithImpl = jest.fn((x) => x * 2);
// Mock implementations
mockFn.mockReturnValue(10);
mockFn.mockReturnValueOnce(5);
mockFn.mockResolvedValue({ data: 'async' });
mockFn.mockRejectedValue(new Error('failed'));
mockFn.mockImplementation((x) => x * 2);
// Assertions
expect(mockFn).toHaveBeenCalled();
expect(mockFn).toHaveBeenCalledTimes(3);
expect(mockFn).toHaveBeenCalledWith(arg1, arg2);
expect(mockFn).toHaveBeenLastCalledWith(arg);
expect(mockFn).toHaveBeenNthCalledWith(2, arg);
expect(mockFn).toHaveReturnedWith(value);
// Mock entire module
jest.mock('./database');
// With implementation
jest.mock('./api', () => ({
fetchUser: jest.fn().mockResolvedValue({ id: 1, name: 'John' }),
updateUser: jest.fn().mockResolvedValue({ success: true })
}));
// Partial mock
jest.mock('./utils', () => ({
...jest.requireActual('./utils'),
formatDate: jest.fn().mockReturnValue('2024-01-01')
}));
// Manual mock (__mocks__/module.js)
// Automatically used when jest.mock('./module') is called
jest.mock('./UserService');
const UserService = require('./UserService');
// Mock instance methods
UserService.prototype.getUser = jest.fn().mockResolvedValue({ id: 1 });
// Or mock the constructor
UserService.mockImplementation(() => ({
getUser: jest.fn().mockResolvedValue({ id: 1 }),
createUser: jest.fn().mockResolvedValue({ id: 2 })
}));
const obj = {
method: () => 'original'
};
// Spy without changing behavior
const spy = jest.spyOn(obj, 'method');
obj.method();
expect(spy).toHaveBeenCalled();
// Spy with mock implementation
jest.spyOn(obj, 'method').mockReturnValue('mocked');
expect(obj.method()).toBe('mocked');
// Restore original
spy.mockRestore();
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.useRealTimers();
});
it('calls callback after delay', () => {
const callback = jest.fn();
setTimeout(callback, 1000);
expect(callback).not.toHaveBeenCalled();
jest.advanceTimersByTime(1000);
expect(callback).toHaveBeenCalled();
});
it('runs all timers', () => {
const callback = jest.fn();
setTimeout(callback, 1000);
setTimeout(callback, 2000);
jest.runAllTimers();
expect(callback).toHaveBeenCalledTimes(2);
});
// Promises
it('resolves with data', async () => {
const data = await fetchData();
expect(data).toEqual({ id: 1 });
});
// Or with resolves/rejects
it('resolves with data', () => {
return expect(fetchData()).resolves.toEqual({ id: 1 });
});
it('rejects with error', () => {
return expect(failingFetch()).rejects.toThrow('Network error');
});
// Callbacks
it('calls callback with data', (done) => {
fetchDataCallback((error, data) => {
try {
expect(error).toBeNull();
expect(data).toEqual({ id: 1 });
done();
} catch (e) {
done(e);
}
});
});
// Async with expect.assertions
it('handles multiple assertions', async () => {
expect.assertions(2);
const data = await fetchData();
expect(data.id).toBe(1);
expect(data.name).toBe('John');
});
// Basic snapshot
it('renders correctly', () => {
const tree = renderer.create(<Button>Click</Button>).toJSON();
expect(tree).toMatchSnapshot();
});
// Inline snapshot
it('returns user object', () => {
const user = getUser(1);
expect(user).toMatchInlineSnapshot(`
Object {
"id": 1,
"name": "John",
}
`);
});
// Custom serializer
expect.addSnapshotSerializer({
test: (val) => val && val.testId,
print: (val) => `TestID: ${val.testId}`
});
// Update snapshots
// Run: jest --updateSnapshot or jest -u
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
describe('LoginForm', () => {
it('renders form fields', () => {
render(<LoginForm />);
expect(screen.getByLabelText(/email/i)).toBeInTheDocument();
expect(screen.getByLabelText(/password/i)).toBeInTheDocument();
expect(screen.getByRole('button', { name: /login/i })).toBeInTheDocument();
});
it('shows error for invalid email', async () => {
const user = userEvent.setup();
render(<LoginForm />);
await user.type(screen.getByLabelText(/email/i), 'invalid');
await user.click(screen.getByRole('button', { name: /login/i }));
expect(screen.getByText(/invalid email/i)).toBeInTheDocument();
});
it('submits form with valid data', async () => {
const onSubmit = jest.fn();
const user = userEvent.setup();
render(<LoginForm onSubmit={onSubmit} />);
await user.type(screen.getByLabelText(/email/i), '[email protected]');
await user.type(screen.getByLabelText(/password/i), 'password123');
await user.click(screen.getByRole('button', { name: /login/i }));
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledWith({
email: '[email protected]',
password: 'password123'
});
});
});
it('renders async content', async () => {
render(<UserProfile userId={1} />);
// Wait for loading to finish
expect(screen.getByText(/loading/i)).toBeInTheDocument();
await waitFor(() => {
expect(screen.getByText(/john doe/i)).toBeInTheDocument();
});
});
});
import axios from 'axios';
jest.mock('axios');
describe('API Service', () => {
it('fetches users', async () => {
const users = [{ id: 1, name: 'John' }];
axios.get.mockResolvedValue({ data: users });
const result = await fetchUsers();
expect(axios.get).toHaveBeenCalledWith('/api/users');
expect(result).toEqual(users);
});
it('handles error', async () => {
axios.get.mockRejectedValue(new Error('Network error'));
await expect(fetchUsers()).rejects.toThrow('Network error');
});
});
// With MSW (Mock Service Worker)
import { setupServer } from 'msw/node';
import { http, HttpResponse } from 'msw';
const server = setupServer(
http.get('/api/users', () => {
return HttpResponse.json([{ id: 1, name: 'John' }]);
})
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
it('fetches users', async () => {
const users = await fetchUsers();
expect(users).toHaveLength(1);
});
# Generate coverage report
jest --coverage
# Coverage thresholds in jest.config.js
coverageThreshold: {
global: {
branches: 80,
functions: 80,
lines: 80,
statements: 80
},
'./src/utils/': {
branches: 100,
statements: 100
}
}
// jest.setup.js
expect.extend({
toBeWithinRange(received, floor, ceiling) {
const pass = received >= floor && received <= ceiling;
if (pass) {
return {
message: () => `expected ${received} not to be within range ${floor} - ${ceiling}`,
pass: true
};
} else {
return {
message: () => `expected ${received} to be within range ${floor} - ${ceiling}`,
pass: false
};
}
}
});
// Usage
expect(100).toBeWithinRange(90, 110);
xiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience