用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
直接命令不会经过审查 Prompt;运行前请先检查来源。
npx skills add https://github.com/tomevault-io/skills-registry --skill jest-test命令会保持在同一行。复制前请横向滚动并检查完整内容。
想先保存到本地?可下载 SkillsMP 当前能够提供的文件。
基于 SOC 职业分类
正在显示 SKILL.md
| name | jest-test |
| description | > Use when this capability is needed. |
Write, review, and improve Jest tests following production-quality patterns and best practices for TypeScript and JavaScript projects.
Before starting, consult references/jest-guide.xml -- a comprehensive playbook covering core principles, the full matcher catalog, async testing patterns, mocking strategies, data-driven tests, error handling, anti-patterns, and CI/CD integration. Reference it throughout the workflow.
Analyze --> Plan --> Write Tests --> Review
^ | |
+---- Revise --------+ |
+-- Fix ------+
Follow steps 1-4 in order. If the user provides existing tests for review, skip to Step 4.
Read the source code to understand what needs testing. Identify:
<mocking> in jest-guide.xml)<async_testing>)If the user provides a file path, read it. If they describe functionality without providing code, ask them to share the relevant source files.
Determine the test strategy before writing code. Decide:
What to test:
<anti_patterns> in jest-guide.xml)Test organization (see <core_principles> for structure templates):
describe block per function, class, or logical grouping'should return empty array when no items match filter'describe blocksMocking strategy (see <mocking> for the full pattern catalog):
jest.spyOn when you need to verify calls while keeping the original behaviorCoverage goals (see <coverage_requirements> in <core_principles>):
Generate tests following the patterns in jest-guide.xml. Apply these rules consistently:
Every test file follows this skeleton:
import { ServiceUnderTest } from '../service-under-test';
// Mock dependencies at the top
jest.mock('../dependency-module');
describe('ServiceUnderTest', () => {
let service: ServiceUnderTest;
let mockDependency: jest.Mocked<DependencyType>;
beforeEach(() => {
// Arrange: fresh instance and mocks for each test
mockDependency = new DependencyModule() as jest.Mocked<DependencyType>;
service = new ServiceUnderTest(mockDependency);
});
afterEach(() => {
jest.clearAllMocks();
jest.restoreAllMocks();
});
describe('methodName', () => {
test('should return expected result for valid input', async () => {
// Arrange
mockDependency.fetch.mockResolvedValue(testData);
// Act
const result = await service.methodName(input);
// Assert
expect(result).(expected);
});
(, () => {
mockDependency..( ());
(service.(input))..();
});
});
});
Select the right matcher from <matchers> in jest-guide.xml:
| Scenario | Matcher | Why |
|---|---|---|
| Primitive comparison | toBe() | Strict === equality |
| Object/array comparison | toEqual() | Deep equality, ignores undefined |
| Strict object comparison | toStrictEqual() | Includes undefined properties |
| Partial object match | toMatchObject() | Only checks specified keys |
| Array contains item | toContain() (primitives) / toContainEqual() (objects) | Subset checking |
| Floating point | toBeCloseTo() | Avoids precision errors |
| Error thrown | toThrow() | Wrap in expect(() => ...) for sync |
All async tests must include assertion counting (see <async_testing>):
test('async operation', async () => {
expect.assertions(1); // Prevents false positives
const result = await service.fetchData();
expect(result).toBeDefined();
});
For error cases, use .rejects:
test('rejects on failure', async () => {
expect.assertions(1);
await expect(service.fetchData()).rejects.toThrow('Network error');
});
Always clean up mocks (see <cleanup> in <mocking>):
afterEach(() => {
jest.clearAllMocks(); // Reset call history
jest.restoreAllMocks(); // Restore original implementations
});
Use test.each for parameterized tests (see <data_driven_testing>):
test.each([
['valid@email.com', true],
['invalid', false],
['', false],
])('validates email "%s" as %s', (email, expected) => {
expect(isValidEmail(email)).toBe(expected);
});
Never include any of the patterns listed in <forbidden_patterns> in jest-guide.xml:
.only or .skip -- these break CIjest.useFakeTimers() (see <timer_mocking>)await and use expect.assertions()Audit tests (generated or user-provided) against the reference. Check each area and report findings.
Check against every item in <anti_patterns> in jest-guide.xml:
afterEachsetTimeout/setInterval -- fake timers used instead.only, .skip, or .todo in committed codeexpect.assertions(n) or expect.hasAssertions().rejects.toThrow()await)afterEach includes jest.clearAllMocks() and/or jest.restoreAllMocks()jest.spyOn used when original behavior should be preservedjest.mock() at the top of the file (hoisting)<coverage_requirements>Check against <ci_cd> quality gates:
.only / .skip / .todoconsole.log statements in test filesPresent review results as a checklist with pass/fail and specific fix recommendations.
User says: "Write tests for this UserService"
Actions:
expect.assertions(), mocks cleaned up in afterEachResult: A complete user-service.test.ts file with tests for each public method, mocked dependencies, error path coverage, and proper cleanup.
User says: "Review my test file for issues"
Actions:
Result: A review report like:
expect.assertions() in async testsetTimeout used instead of fake timersafterEach cleanup -- mock state may leak between teststest.each for the repetitive validation tests on lines 60-90User says: "How do I mock this external API client?"
Actions:
<mocking> in jest-guide.xmljest.mock() for the module and mockResolvedValue / mockRejectedValue for async methodsResult: A focused code snippet showing module mock setup, typed mocks, return value configuration, and cleanup -- ready to paste into the test file.
Cause: Test order dependency -- a mock or state from one test leaks into another. Tests run in a different order in CI.
Solution: Add afterEach(() => { jest.clearAllMocks(); jest.restoreAllMocks(); }) to every describe block. Run locally with --runInBand to reproduce order-dependent failures. Check for shared mutable state outside of beforeEach.
Cause: jest.mock() calls are hoisted to the top of the file, but the mock path may not match the import path exactly. Or jest.doMock() was used without a subsequent dynamic require().
Solution: Ensure the path in jest.mock('path') exactly matches the import statement. For aliased paths (@/services/...), verify moduleNameMapper in Jest config. Check that the mock is defined before the module-under-test is imported.
Cause: A promise is never resolved or rejected, or done() is never called in a callback-style test.
Solution: Check that all async operations are properly awaited. For callback tests, ensure done() is called in both success and error paths (wrap in try/catch). Add expect.assertions(n) to catch silent non-execution. Increase timeout if the operation is legitimately slow: test('slow op', async () => {...}, 10000).
Cause: Uncovered branches (often error paths, default switch cases, or early returns).
Solution: Run jest --coverage and inspect the HTML report at coverage/lcov-report/index.html. Look for red-highlighted lines -- these are uncovered. Common gaps: catch blocks, null checks, default cases in switch statements. Add targeted tests for each uncovered branch.
Source: AgentCTO/claude-skills — distributed by TomeVault.