Testing Basics
Jest · Reference cheat sheet
Jest · Reference cheat sheet
📋 Overview
Jest is a zero/low-config JS test runner with built-in matchers, mocks, and coverage. Files: *.test.js|ts / *.spec.js|ts. Structure with describe / test (it).
🔧 Core concepts
| Idea | Practice |
|---|---|
| AAA | Arrange → Act → Assert |
| Matchers | expect(...).toBe / toEqual |
| Mocks | jest.fn / jest.mock |
| Async | async/await + .resolves |
| Watch | jest --watch while coding |
💡 Examples
Minimal:
function add(a, b) {
return a + b;
}
test('adds numbers', () => {
expect(add(2, 3)).toBe(5);
});Group:
describe('cart', () => {
test('starts empty', () => {
expect([]).toHaveLength(0);
});
});Run:
npx jest
npx jest auth.test.ts -t "login"
npx jest --coverage⚠️ Pitfalls
toBeis reference equality — usetoEqualfor objects.- Forgotten
awaitpasses false greens. - Snapshot spam — prefer explicit field asserts for APIs.