Full answer
Structure: describe('name', () => { ... }) groups tests, it('does something', () => { ... }) or test(...) defines one. Hooks (beforeEach, afterEach, beforeAll, afterAll) set up and clean up shared state. A good test follows arrange, act, assert: prepare the input, call the code, check the result. Each test must be independent and not rely on the order of other tests.
Assertions: expect(value).toBe(3) for primitives and identity, toEqual for deep equality of objects and arrays, toStrictEqual to also check undefined properties and types, toThrow for errors, toContain, toMatchObject, and resolves and rejects for promises. Snapshot tests store the output and compare later, which is quick to write and noisy to maintain, so use them for small stable outputs.
Mocks: a mock function (jest.fn() in Jest, vi.fn() in Vitest) records calls and can return fixed values: fn.mockReturnValue(5), expect(fn).toHaveBeenCalledWith('a'). Use mocks to replace slow or external dependencies, such as network, time, and randomness. Prefer passing dependencies in as arguments, which makes mocking easy, over patching modules. A spy (jest.spyOn, vi.spyOn) wraps a real method so you can observe it, and restoring spies after each test avoids leaks between tests.
Async code: return the promise, or use async tests with await, or await expect(promise).rejects.toThrow(). A test that forgets to await can pass even if the code fails, because it finished before the assertion ran.
Timers: fake timers (jest.useFakeTimers(), vi.useFakeTimers()) replace setTimeout and Date so you can advance time (advanceTimersByTime(1000)) with no real waiting. This is the right way to test debounce, retries, and timeouts.
Good practice: test behavior and public results, not private details, keep tests fast and deterministic (no real network, no real clock, no random values without a seed), cover edge cases and error paths, and run tests in continuous integration. Coverage numbers show what is not tested, not whether tests are good. Vitest is faster for Vite projects and ES modules, and Jest is widely used with a large ecosystem. The newer built-in node:test runner needs no installation.
The snippet below uses only Node.js built-ins (node:assert, and the mock tools of node:test), with the same ideas. The Jest and Vitest calls in the answer text were not run here.
const assert = require('node:assert/strict');
const { mock } = require('node:test');
// code under test
function debounce(fn, wait) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), wait);
};
}
async function loadUser(fetchUser, id) {
if (!Number.isInteger(id)) throw new TypeError('id must be an integer');
const user = await fetchUser(id);
return { ...user, name: user.name.toUpperCase() };
}
const sum = (numbers) => numbers.reduce((total, n) => total + n, 0);
// a tiny runner with describe and it, so the output is easy to read
const results = [];
const tests = [];
let prefix = '';
const describe = (name, body) => {
const outer = prefix;
prefix += name + ' > ';
body();
prefix = outer;
};
const it = (name, test) => tests.push({ name: prefix + name, test });
describe('sum', () => {
it('adds numbers', () => assert.equal(sum([1, 2, 3]), 6));
it('returns 0 for an empty list', () => assert.equal(sum([]), 0));
it('fails on purpose to show a failure (error on purpose)', () => assert.equal(sum([1, 1]), 3));
});
describe('loadUser', () => {
it('uppercases the name and calls the fetcher once with the id', async () => {
const fetchUser = mock.fn(async () => ({ id: 7, name: 'asha' }));
const user = await loadUser(fetchUser, 7);
assert.deepEqual(user, { id: 7, name: 'ASHA' });
assert.equal(fetchUser.mock.callCount(), 1);
assert.deepEqual(fetchUser.mock.calls[0].arguments, [7]);
});
it('rejects for a bad id and never calls the fetcher', async () => {
const fetchUser = mock.fn();
await assert.rejects(() => loadUser(fetchUser, 'x'), { name: 'TypeError', message: 'id must be an integer' });
assert.equal(fetchUser.mock.callCount(), 0);
});
it('passes the failure of the fetcher on', async () => {
await assert.rejects(() => loadUser(async () => { throw new Error('offline'); }, 1), /offline/);
});
});
describe('debounce with fake timers', () => {
it('calls once after the wait, with the last arguments', () => {
mock.timers.enable({ apis: ['setTimeout'] });
try {
const spy = mock.fn();
const debounced = debounce(spy, 100);
debounced('a');
debounced('b');
debounced('c');
mock.timers.tick(99);
assert.equal(spy.mock.callCount(), 0);
mock.timers.tick(1);
assert.equal(spy.mock.callCount(), 1);
assert.deepEqual(spy.mock.calls[0].arguments, ['c']);
} finally {
mock.timers.reset();
}
});
});
(async () => {
for (const { name, test } of tests) {
try {
await test();
results.push(`PASS ${name}`);
} catch (error) {
results.push(`FAIL ${name}: ${error.message.split('\n')[0]}`);
}
}
console.log(results.join('\n'));
console.log(`${results.filter((line) => line.startsWith('PASS')).length} passed, ${results.filter((line) => line.startsWith('FAIL')).length} failed`);
})();Run with Node.js v24.22.1 as js-146.js; two runs gave identical output. Output: PASS sum > adds numbers PASS sum > returns 0 for an empty list FAIL sum > fails on purpose to show a failure (error on purpose): Expected values to be strictly equal: PASS loadUser > uppercases the name and calls the fetcher once with the id PASS loadUser > rejects for a bad id and never calls the fetcher PASS loadUser > passes the failure of the fetcher on PASS debounce with fake timers > calls once after the wait, with the last arguments 6 passed, 1 failed
Key points
- Organize with describe and it; follow arrange, act, assert; keep tests independent.
- Use toBe for primitives, toEqual for deep equality, toThrow and rejects for errors.
- Mock functions replace external dependencies and record calls; prefer dependency injection.
- Await promises in async tests; use fake timers for debounce, retries, and timeouts.
- Test behavior, keep tests deterministic, and treat coverage as a hint.
Common mistakes
- Forgetting to await an async test, so it passes before the assertion runs.
- Testing private implementation details, so refactoring breaks tests that should still pass.
- Using real timers, real network calls, or the real clock in unit tests.
- Sharing state between tests and relying on their order.
Follow-ups
- What is the difference between a mock, a stub, and a spy?
- When are snapshot tests useful, and when are they harmful?
- How do you test code that uses the current date or random numbers?
Tips
- Describe arrange, act, assert and test independence.
- Mention dependency injection as the way to make code testable.
- Say that you test behavior, and use fake timers for time.