jest
БесплатноБез исполняемых скриптовНе проверенJest testing framework. Covers unit tests, mocking, and snapshots. Use for testing React and Node.js projects. USE WHEN: user mentions "jest", "jest test"…
от claude-dev-suite★ 51 звезда на GitHubОб этом скилле
Jest Core Knowledge
Deep Knowledge: Use
mcp__documentation__fetch_docswith technology:jestfor comprehensive documentation.
When NOT to Use This Skill
- E2E Testing - Use
playwrightorcypressfor browser automation - Vite Projects - Use
vitestwhich is faster and Vite-native - Component Testing Alone - Combine with
testing-libraryfor React/Vue components - API Integration Tests - Use framework-specific skills (spring-boot-integration, etc.)
Basic Test
describe('UserService', () => {
let service: UserService;
beforeEach(() => {
service = new UserService();
});
afterEach(() => {
jest.clearAllMocks();
});
it('should create user', async () => {
const user = await service.create({ name: 'John' });
expect(user.name).toBe('John');
});
});
Mocking
// Mock function
const mockFn = jest.fn();
mockFn.mockReturnValue(42);
mockFn.mockResolvedValue({ data: [] });
// Mock module
jest.mock('./api', () => ({
fetchUsers: jest.fn().mockResolvedValue([])
}));
// Spy
const spy = jest.spyOn(console, 'log');
expect(spy).toHaveBeenCalledWith('message');
// Mock implementation
mockFn.mockImplementation((x) => x * 2);
Matchers
// Same as Vitest, Jest-compatible
expect(value).toBe(exact);
expect(value).toEqual(deepEqual);
expect(obj).toMatchObject({ name: 'John' });
expect(arr).toContainEqual({ id: 1 });
Snapshots
it('should match snapshot', () => {
const component = render(<UserCard user={user} />);
expect(component).toMatchSnapshot();
});
it('should match inline snapshot', () => {
expect(formatDate(date)).toMatchInlineSnapshot(`"2024-01-15"`);
});
Async Testing
it('should resolve', async () => {
await expect(fetchData()).resolves.toEqual({ data: [] });
});
it('should reject', async () => {
await expect(fetchFail()).rejects.toThrow('Error');
});
Config
// jest.config.js
module.exports = {
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
moduleNameMapper: { '^@/(.*)$': '<rootDir>/src/$1' }
};
Production Readiness
Test Organization
// Isolated tests with proper setup/teardown
describe('OrderService', () => {
let service: OrderService;
let mockRepository: jest.Mocked<OrderRepository>;
beforeEach(() => {
mockRepository = {
findById: jest.fn(),
save: jest.fn(),
delete: jest.fn(),
} as jest.Mocked<OrderRepository>;
service = new OrderService(mockRepository);
});
afterEach(() => {
jest.clearAllMocks();
});
describe('processOrder', () => {
it('should process valid order', async () => {
// Arrange
const order = createTestOrder({ status: 'pending' });
mockRepository.findById.mockResolvedValue(order);
mockRepository.save.mockResolvedValue({ ...order, status: 'processed' });
// Act
const result = await service.processOrder(order.id);
// Assert
expect(result.status).toBe('processed');
expect(mockRepository.save).toHaveBeenCalledWith(
expect.objectContaining({ status: 'processed' })
);
});
});
});
Coverage Configuration
// jest.config.js
module.exports = {
collectCoverageFrom: [
'src/**/*.{ts,tsx}',
'!src/**/*.d.ts',
'!src/**/index.ts',
'!src/**/*.stories.tsx',
],
coverageThreshold: {
global: {
branches: 75,
functions: 80,
lines: 80,
statements: 80,
},
},
coverageReporters: ['text', 'lcov', 'html'],
};
CI Integration
# GitHub Actions
- name: Run tests
run: npm test -- --ci --coverage --reporters=default --reporters=jest-junit
env:
JEST_JUNIT_OUTPUT_DIR: ./reports
- name: Upload coverage
uses: codecov/codecov-action@v3
// package.json
{
"scripts": {
"test": "jest",
"test:ci": "jest --ci --coverage --maxWorkers=2",
"test:watch": "jest --watch"
}
}
Performance Optimization
// jest.config.js - Speed up tests
module.exports = {
// Run tests in parallel
maxWorkers: '50%',
// Cache transformations
cacheDirectory: '<rootDir>/.jest-cache',
// Only run affected tests
onlyChanged: true,
// Fail fast in CI
bail: process.env.CI ? 1 : 0,
};
Monitoring Metrics
| Metric | Target |
|---|---|
| Line coverage | > 80% |
| Branch coverage | > 75% |
| Test execution time | < 120s |
| Flaky test rate | 0% |
Checklist
- Arrange-Act-Assert pattern
- Isolated tests (no shared state)
- Coverage thresholds enforced
- CI/CD integration with reporting
- jest.clearAllMocks() in afterEach
- Meaningful test descriptions
- Async tests properly awaited
- Snapshot tests reviewed
- Test data factories
- Error scenarios covered
Anti-Patterns
| Anti-Pattern | Why It's Bad | Solution |
|---|
Установить jest в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadGrepGlobWriteEditВложенные файлы
FAQ
Что делает скилл jest?
Jest testing framework. Covers unit tests, mocking, and snapshots. Use for testing React and Node.js projects. USE WHEN: user mentions "jest", "jest test", "snapshot test", asks about "jest.fn", "jest.mock", "toMatchSnapshot", "React testing" DO NOT USE FOR: E2E tests - use `playwright` or `cypress`; Vite projects - use `vitest` instead; React component testing alone - combine with `testing-library`
Как установить скилл jest?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл jest запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic