jest-skill – skill Lập trình cho agent AI
Tạo test unit và integration với Jest trong JavaScript hoặc TypeScript. Bao gồm mocking, snapshot, kiểm thử async và kiểm thử component React. Dùng khi người dùng nhắc đến "Jest", "describe/it/expect", "jest.mock", "toMatchSnapshot".
Cài skill jest-skill bằng một lệnh
Chọn công cụ bạn đang dùng, copy lệnh và dán vào terminal. Skill sẽ nằm trong thư mục skills của công cụ đó và sẵn sàng dùng ở phiên làm việc tiếp theo.
Claude Code
mkdir -p ~/.claude/skills && curl -fsSL https://skill.dn1nguoi.com/z/jest-skill-43499.tgz | tar xz -C ~/.claude/skills
Gọi trong Claude Code: /jest-skill – rồi mô tả công việc bạn muốn làm.
Codex
mkdir -p ~/.codex/skills && curl -fsSL https://skill.dn1nguoi.com/z/jest-skill-43499.tgz | tar xz -C ~/.codex/skills
Gọi trong Codex: $jest-skill – rồi mô tả công việc bạn muốn làm.
Hermes Agent
mkdir -p ~/.hermes/skills && curl -fsSL https://skill.dn1nguoi.com/z/jest-skill-43499.tgz | tar xz -C ~/.hermes/skills
Gọi trong Hermes Agent: /jest-skill – rồi mô tả công việc bạn muốn làm.
DeepSeek
mkdir -p ~/.deepcode/skills && curl -fsSL https://skill.dn1nguoi.com/z/jest-skill-43499.tgz | tar xz -C ~/.deepcode/skills
Gọi trong DeepSeek: /jest-skill – rồi mô tả công việc bạn muốn làm.
Nội dung SKILL.md
Nội dung SKILL.md gốc bằng tiếng Anh.
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",...
Examples are separate fragments needing actual implementation imports and the project Jest environment/transforms. The reference/playbook.md file is not bundled. CommonJS jest.mock examples do not directly apply to native ESM; inspect the installed version. Restore spies/timers in afterEach/finally even on assertion failure; remove test.only before committing. Update snapshots only after reviewing the intended semantic change, never to silence failures.
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' });
mockFn('arg1');
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();
console.log('expected');
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 onSubmit = jest.fn();
render(<LoginForm onSubmit={onSubmit} />);
fireEvent.change(screen.getByLabelText('Email'), {
target: { value: '[email protected]' },
});
fireEvent.change(screen.getByLabelText('Password'), {
target: { value: 'password123' },
});
fireEvent.click(screen.getByRole('button', { name: /login/i }));
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledWith({
email: '[email protected]', password: 'password123',
});
});
});Snapshot Testing
test('renders correctly', () => {
const tree = renderer.create(<Button label="Click" />).toJSON();
expect(tree).toMatchSnapshot();
});
// Update: jest --updateSnapshotAnti-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.
Skill liên quan
- testrail – Đồng bộ test với TestRail. Dùng khi người dùng nhắc đến "testrail", "test management"…
- js-reverse – Dịch ngược JavaScript phía front-end: xác định chuỗi chữ ký, phân tích tham số request…
- json-schema-manual – Hướng dẫn JSON Schema: tạo schema xác thực draft 2020-12 từ danh sách trường đã xác…
- junit-5-skill – Tạo test unit và integration JUnit 5 cho Java đạt chuẩn production. Bao gồm assertion…
- k6-load-testing – Skill kiểm thử tải k6 toàn diện cho API, trình duyệt và kiểm thử khả năng mở rộng. Viết…
- kaizen – Hướng dẫn cải tiến liên tục, phòng ngừa lỗi và chuẩn hóa. Dùng skill này khi người dùng…
- kimi-delegate – Giao tác vụ lập trình cho Kimi Code CLI (`kimi`) chỉ khi người dùng yêu cầu rõ ràng…
- kotlin – Hướng dẫn super-code theo ngôn ngữ cho Kotlin.