Jest Cheat Sheet: Matchers, Mocks & CLI Flags
Jest matchers, mocks, and CLI flags in one quick reference.
Assert, mock, and run JavaScript tests with Jest.
CLI flags
| Flag | Does |
|---|---|
| jest -t "name" | Run tests matching name |
| jest path.test.js | Run one file |
| jest --watch | Watch changed files |
| jest -u | Update snapshots |
| jest --coverage | Collect coverage |
| jest --ci | CI mode (no snapshot writes) |
| jest --runInBand | Serial (debugging) |
Matchers
| Matcher | Asserts |
|---|---|
| toBe(x) | Strict equality |
| toEqual(x) | Deep equality |
| toContain(x) | Array/string contains |
| toThrow() | Function throws |
| toHaveBeenCalledWith(a) | Mock called with args |
| resolves / rejects | Async promise outcome |
Mocks & hooks
example.test.js
const fn = jest.fn().mockReturnValue(1);
jest.mock('./api');
beforeEach(() => jest.clearAllMocks());
test('async', async () => {
await expect(fetchUser()).resolves.toEqual({ id: 1 });
});Key takeaways
- toBe is reference/primitive equality; toEqual deep-compares.
- --ci fails instead of writing new snapshots.
- clearAllMocks in beforeEach keeps tests isolated.
Related guides
pytest Cheat Sheet: Selectors, Fixtures & MarkersA pytest cheat sheet - test selection, fixtures, markers, parametrize, assertions, and the CLI flags you reac…
npm Scripts Cheat Sheet: Commands, Lifecycle & CI FlagsAn npm scripts cheat sheet - run, ci, install, lifecycle hooks, pre/post scripts, and the npm flags you use i…
Exit Codes Cheat Sheet: Shell Status Codes ExplainedAn exit codes cheat sheet - what 0, 1, 2, 126, 127, 130, and signal-derived codes mean, and how to read $? in…