$npx -y skills add github/awesome-copilot --skill javascript-typescript-jestBest practices for writing JavaScript/TypeScript tests using Jest, including mocking strategies, test structure, and common patterns.
| 1 | ### Test Structure |
| 2 | - Name test files with `.test.ts` or `.test.js` suffix |
| 3 | - Place test files next to the code they test or in a dedicated `__tests__` directory |
| 4 | - Use descriptive test names that explain the expected behavior |
| 5 | - Use nested describe blocks to organize related tests |
| 6 | - Follow the pattern: `describe('Component/Function/Class', () => { it('should do something', () => {}) })` |
| 7 | |
| 8 | ### Effective Mocking |
| 9 | - Mock external dependencies (APIs, databases, etc.) to isolate your tests |
| 10 | - Use `jest.mock()` for module-level mocks |
| 11 | - Use `jest.spyOn()` for specific function mocks |
| 12 | - Use `mockImplementation()` or `mockReturnValue()` to define mock behavior |
| 13 | - Reset mocks between tests with `jest.resetAllMocks()` in `afterEach` |
| 14 | |
| 15 | ### Testing Async Code |
| 16 | - Always return promises or use async/await syntax in tests |
| 17 | - Use `resolves`/`rejects` matchers for promises |
| 18 | - Set appropriate timeouts for slow tests with `jest.setTimeout()` |
| 19 | |
| 20 | ### Snapshot Testing |
| 21 | - Use snapshot tests for UI components or complex objects that change infrequently |
| 22 | - Keep snapshots small and focused |
| 23 | - Review snapshot changes carefully before committing |
| 24 | |
| 25 | ### Testing React Components |
| 26 | - Use React Testing Library over Enzyme for testing components |
| 27 | - Test user behavior and component accessibility |
| 28 | - Query elements by accessibility roles, labels, or text content |
| 29 | - Use `userEvent` over `fireEvent` for more realistic user interactions |
| 30 | |
| 31 | ## Common Jest Matchers |
| 32 | - Basic: `expect(value).toBe(expected)`, `expect(value).toEqual(expected)` |
| 33 | - Truthiness: `expect(value).toBeTruthy()`, `expect(value).toBeFalsy()` |
| 34 | - Numbers: `expect(value).toBeGreaterThan(3)`, `expect(value).toBeLessThanOrEqual(3)` |
| 35 | - Strings: `expect(value).toMatch(/pattern/)`, `expect(value).toContain('substring')` |
| 36 | - Arrays: `expect(array).toContain(item)`, `expect(array).toHaveLength(3)` |
| 37 | - Objects: `expect(object).toHaveProperty('key', value)` |
| 38 | - Exceptions: `expect(fn).toThrow()`, `expect(fn).toThrow(Error)` |
| 39 | - Mock functions: `expect(mockFn).toHaveBeenCalled()`, `expect(mockFn).toHaveBeenCalledWith(arg1, arg2)` |