javascript-typescript-jest
Installation
Summary
Jest testing best practices for JavaScript and TypeScript projects with mocking, async handling, and React patterns.
- Organize tests with descriptive names in nested
describeblocks, using.test.ts/.test.jsfiles placed alongside source code or in__tests__directories - Mock external dependencies with
jest.mock(),jest.spyOn(), andmockImplementation(), resetting between tests to prevent state leakage - Handle async code with promises,
async/await, andresolves/rejectsmatchers; set timeouts for slow tests - Test React components with React Testing Library, querying by accessibility roles and labels, and using
userEventfor realistic interactions - Includes 20+ common matchers covering truthiness, numbers, strings, arrays, objects, exceptions, and mock function assertions
SKILL.md
Test Structure
- Name test files with
.test.tsor.test.jssuffix - Place test files next to the code they test or in a dedicated
__tests__directory - Use descriptive test names that explain the expected behavior
- Use nested describe blocks to organize related tests
- Follow the pattern:
describe('Component/Function/Class', () => { it('should do something', () => {}) })
Effective Mocking
- Mock external dependencies (APIs, databases, etc.) to isolate your tests
- Use
jest.mock()for module-level mocks - Use
jest.spyOn()for specific function mocks - Use
mockImplementation()ormockReturnValue()to define mock behavior - Reset mocks between tests with
jest.resetAllMocks()inafterEach
Testing Async Code
- Always return promises or use async/await syntax in tests
- Use
resolves/rejectsmatchers for promises - Set appropriate timeouts for slow tests with
jest.setTimeout()