$npx -y skills add LambdaTest/agent-skills --skill jest-skillGenerates 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",
| 1 | # Jest Testing Skill |
| 2 | |
| 3 | ## Core Patterns |
| 4 | |
| 5 | ### Basic Test |
| 6 | |
| 7 | ```javascript |
| 8 | describe('Calculator', () => { |
| 9 | let calc; |
| 10 | beforeEach(() => { calc = new Calculator(); }); |
| 11 | |
| 12 | test('adds two numbers', () => { |
| 13 | expect(calc.add(2, 3)).toBe(5); |
| 14 | }); |
| 15 | |
| 16 | test('throws on division by zero', () => { |
| 17 | expect(() => calc.divide(10, 0)).toThrow('Division by zero'); |
| 18 | }); |
| 19 | }); |
| 20 | ``` |
| 21 | |
| 22 | ### Matchers |
| 23 | |
| 24 | ```javascript |
| 25 | expect(value).toBe(exact); // === strict |
| 26 | expect(value).toEqual(object); // deep equality |
| 27 | expect(value).toBeTruthy(); |
| 28 | expect(value).toBeNull(); |
| 29 | expect(value).toBeGreaterThan(3); |
| 30 | expect(value).toBeCloseTo(0.3, 5); |
| 31 | expect(str).toMatch(/regex/); |
| 32 | expect(arr).toContain(item); |
| 33 | expect(arr).toHaveLength(3); |
| 34 | expect(obj).toHaveProperty('name'); |
| 35 | expect(obj).toMatchObject({ name: 'Alice' }); |
| 36 | expect(() => fn()).toThrow(CustomError); |
| 37 | ``` |
| 38 | |
| 39 | ### Mocking |
| 40 | |
| 41 | ```javascript |
| 42 | // Mock function |
| 43 | const mockFn = jest.fn(); |
| 44 | mockFn.mockReturnValue(42); |
| 45 | mockFn.mockResolvedValue({ data: 'test' }); |
| 46 | expect(mockFn).toHaveBeenCalledWith('arg1'); |
| 47 | expect(mockFn).toHaveBeenCalledTimes(1); |
| 48 | |
| 49 | // Mock module |
| 50 | jest.mock('./database'); |
| 51 | const db = require('./database'); |
| 52 | db.getUser.mockResolvedValue({ name: 'Alice' }); |
| 53 | |
| 54 | // Mock with implementation |
| 55 | jest.mock('./api', () => ({ |
| 56 | fetchUsers: jest.fn().mockResolvedValue([{ name: 'Alice' }]), |
| 57 | })); |
| 58 | |
| 59 | // Spy |
| 60 | const spy = jest.spyOn(console, 'log').mockImplementation(); |
| 61 | expect(spy).toHaveBeenCalledWith('expected'); |
| 62 | spy.mockRestore(); |
| 63 | |
| 64 | // Fake timers |
| 65 | jest.useFakeTimers(); |
| 66 | jest.advanceTimersByTime(1000); |
| 67 | jest.useRealTimers(); |
| 68 | ``` |
| 69 | |
| 70 | ### Async Testing |
| 71 | |
| 72 | ```javascript |
| 73 | test('fetches users', async () => { |
| 74 | const users = await fetchUsers(); |
| 75 | expect(users).toHaveLength(3); |
| 76 | }); |
| 77 | |
| 78 | test('resolves with data', () => { |
| 79 | return expect(fetchData()).resolves.toEqual({ data: 'value' }); |
| 80 | }); |
| 81 | |
| 82 | test('rejects with error', () => { |
| 83 | return expect(fetchBadData()).rejects.toThrow('not found'); |
| 84 | }); |
| 85 | ``` |
| 86 | |
| 87 | ### React Component Testing (Testing Library) |
| 88 | |
| 89 | ```javascript |
| 90 | import { render, screen, fireEvent, waitFor } from '@testing-library/react'; |
| 91 | import '@testing-library/jest-dom'; |
| 92 | import LoginForm from './LoginForm'; |
| 93 | |
| 94 | test('submits login form', async () => { |
| 95 | const onSubmit = jest.fn(); |
| 96 | render(<LoginForm onSubmit={onSubmit} />); |
| 97 | |
| 98 | fireEvent.change(screen.getByLabelText('Email'), { |
| 99 | target: { value: 'user@test.com' }, |
| 100 | }); |
| 101 | fireEvent.change(screen.getByLabelText('Password'), { |
| 102 | target: { value: 'password123' }, |
| 103 | }); |
| 104 | fireEvent.click(screen.getByRole('button', { name: /login/i })); |
| 105 | |
| 106 | await waitFor(() => { |
| 107 | expect(onSubmit).toHaveBeenCalledWith({ |
| 108 | email: 'user@test.com', password: 'password123', |
| 109 | }); |
| 110 | }); |
| 111 | }); |
| 112 | ``` |
| 113 | |
| 114 | ### Snapshot Testing |
| 115 | |
| 116 | ```javascript |
| 117 | test('renders correctly', () => { |
| 118 | const tree = renderer.create(<Button label="Click" />).toJSON(); |
| 119 | expect(tree).toMatchSnapshot(); |
| 120 | }); |
| 121 | // Update: jest --updateSnapshot |
| 122 | ``` |
| 123 | |
| 124 | ### Anti-Patterns |
| 125 | |
| 126 | | Bad | Good | Why | |
| 127 | |-----|------|-----| |
| 128 | | `expect(x === y).toBe(true)` | `expect(x).toBe(y)` | Better errors | |
| 129 | | No `await` on async | Always `await` | Swallows failures | |
| 130 | | Snapshot everything | Snapshot UI, assert logic | Snapshot fatigue | |
| 131 | |
| 132 | ## Quick Reference |
| 133 | |
| 134 | | Task | Command | |
| 135 | |------|---------| |
| 136 | | Run all | `npx jest` | |
| 137 | | Watch | `npx jest --watch` | |
| 138 | | Coverage | `npx jest --coverage` | |
| 139 | | Update snapshots | `npx jest --updateSnapshot` | |
| 140 | | Run file | `npx jest tests/calc.test.js` | |
| 141 | | Single test | `test.only('name', () => {})` | |
| 142 | |
| 143 | ## Deep Patterns |
| 144 | |
| 145 | For production-grade patterns, see `reference/playbook.md`: |
| 146 | |
| 147 | | Section | What's Inside | |
| 148 | |---------|--------------| |
| 149 | | §1 Production Config | Node + React configs, path aliases, coverage thresholds | |
| 150 | | §2 Mocking Deep Dive | Module/partial/manual mocks, spies, timers, env vars | |
| 151 | | §3 Async Patterns | Promises, rejections, event emitters, streams | |
| 152 | | §4 test.each | Array, tagged template, describe.each for table-driven tests | |
| 153 | | §5 Custom Matchers | toBeWithinRange, toBeValidEmail, TypeScript declarations | |
| 154 | | §6 React Testing Library | userEvent, hooks, context providers | |
| 155 | | §7 Snapshot Testing | Component, inline, property matchers | |
| 156 | | §8 API Service Testing | Mocked axios, CRUD patterns, error handling | |
| 157 | | §9 Global Setup | Multi-project config, DB setup/teardown | |
| 158 | | §10 CI/CD | GitHub Actions with coverage gates | |
| 159 | | §11 Debugging Table | 10 common problems with fixes | |
| 160 | | §12 Best Practices | 15-item production checklist | |