Jest Testing Skill
Generate complete Jest test suites in seconds, not hours
❌ Writing comprehensive test coverage for JavaScript and TypeScript projects is time-consuming and error-prone without a structured approach.
✅ Users get production-ready Jest tests with proper mocking, snapshots, and async handling that validate their code reliably.
- ✓Generates unit and integration tests for JavaScript and TypeScript
- ✓Handles mocking, snapshots, async testing, and React components
- ✓Includes test setup, assertions, and error case coverage
- ✓Supports describe/it/expect patterns and jest.mock utilities
👁 3 views · 📦 0 installs
Free to install — no account needed
Copy the command below and paste into your agent.
Instant access • No coding needed • No account needed
What you get in 5 minutes
- Full skill code ready to install
- Works with 7 AI agents
- Lifetime updates included
Run this helper
Answer a few questions and let this helper do the work.
▸Advanced: use with your AI agent
Description
--- name: jest-skill description: > 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", "snapshot test", "JS test", "React test". languages: - JavaScript - TypeScript category: unit-testing license: MIT metadata: author: TestMu AI version: "1.0" --- # Jest Testing Skill ## Core Patterns ### Basic Test ```javascript 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 ```javascript 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 ```javascript // Mock function const mockFn = jest.fn(); mockFn.mockReturnValue(42); mockFn.mockResolvedValue({ data: 'test' }); 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(); expect(spy).toHaveBeenCalledWith('expected'); spy.mockRestore(); // Fake timers jest.useFakeTimers(); jest.advanceTimersByTime(1000); jest.useRealTimers(); ``` ### Async Testing ```javascript 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) ```javascript 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 ```javascript test('renders correctly', () => { const tree = renderer.create(<Button label="Click" />).toJSON(); expect(tree).toMatchSnapshot(); }); // Update: jest --updateSnapshot ``` ### Anti-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 |
Security Status
Unvetted
Not yet security scanned
Related AI Tools
More Career Boost tools you might like
ru-text — Russian Text Quality
FreeApplies professional Russian typography, grammar, and style rules to improve text quality across content types
/forge:工作流总入口
Free'Forge 工作流总入口。检查项目状态,推荐下一步该用哪个 skill。任何时候不知道下一步该干什么,就用 /forge。触发方式:用户说"forge"、"下一步"、"接下来做什么"、"继续"(在没有明确上下文时)。'
TypeScript React & Next.js Production Patterns
FreeProduction-grade TypeScript reference for React & Next.js covering type safety, component patterns, API validation, state management, and debugging
Charles Proxy Session Extractor
FreeExtracts HTTP/HTTPS request and response data from Charles Proxy session files (.chlsj format), including URLs, methods, status codes, headers, request bodies, and response bodies. Use when analyzing captured network traffic from Charles Proxy debug
Java Backend Interview Simulator
FreeSimulates realistic Java backend technical interviews with customizable interviewer styles and candidate levels for Chinese tech companies
AI News & Trends Intelligence
FreeFetches latest AI/ML news, trending open-source projects, and social media discussions from 75+ curated sources for comprehensive AI briefings