JavaScript and TypeScript course ยท Module 11: Testing with Jest
Testing Asynchronous Code
In this lesson3
Scanning a DNA sample does not finish the moment the function is called. The result arrives later, as a promise (Promise), and a test that does not wait for it will finish before the result arrives and report success without having checked anything. That false sense of safety is more dangerous than a red alarm.
In Jurassic Park, many operations are asynchronous - DNA scanning, communicating with sensors, fetching data from satellites. Jest offers several ways to test such code.
Testing Promises
async/await
The most readable way to test asynchronous code takes two steps: mark the test function as async and use await when calling the function under test. We assume that fetch has been replaced with a mock here, as in the previous lesson, and returns a T-Rex sample with a purity of 0.95:
// Asynchronous function to test
async function scanDNA(sampleId) {
const response = await fetch(`/api/dna/${sampleId}`);
const data = await response.json();
return {
species: data.species,
purity: data.purity,
viable: data.purity > 0.9
};
}
// Test with async/await
test('DNA scanning returns species', async () => {
const result = await scanDNA('SAMPLE-001');
expect(result.species).toBe('T-Rex');
expect(result.purity).toBeGreaterThan(0.9);
expect(result.viable).toBe(true);
});Jest sees that the test function returns a promise and waits for it before judging the result. Without await, the result variable would be a promise rather than an object, so result.species would give undefined. The scanDNA function itself does not change - the only change is that the test patiently waits for its answer.
resolves and rejects
Jest has dedicated matchers for Promises. .resolves unwraps the value of a fulfilled promise and .rejects the reason for a rejection, after which you add an ordinary matcher. You put await in front of the whole expression (or return it with return). For the INVALID sample, our fetch mock rejects the promise with a "Sample not found" error:
// Testing resolve
test('DNA scan resolves with data', async () => {
await expect(scanDNA('SAMPLE-001')).resolves.toEqual({
species: 'T-Rex',
purity: 0.95,
viable: true
});
});
// Testing reject
test('DNA scan rejects for invalid sample', async () => {
await expect(scanDNA('INVALID')).rejects.toThrow('Sample not found');
});A missing await before expect is a classic mistake: the test ends before the matcher checks anything. The same rule applies to async functions that throw exceptions themselves - like a defense system that refuses to activate without a zone number:
// Another example - testing a rejected Promise
async function activateDefense(zoneId) {
if (!zoneId) {
throw new Error('Zone ID is required');
}
return { status: 'activated', zone: zoneId };
}
test('defense rejects without zone ID', async () => {
await expect(activateDefense(null)).rejects.toThrow('Zone ID is required');
});
test('defense resolves with valid zone', async () => {
await expect(activateDefense('A')).resolves.toEqual({
status: 'activated',
zone: 'A'
});
});activateDefense is an async function, so a throw inside it does not explode immediately but turns into a rejected promise. That is why we test it with rejects.toThrow rather than the expect(() => ...).toThrow() you know from the matchers lesson. If you prefer a classic try/catch, add expect.assertions(1) at the start of the test. Then a promise that unexpectedly fulfills will not slip past the catch block without any assertion.
Testing Callbacks
Older code does not return promises. Instead, it accepts a callback, that is, a function called with the result. Following the Node.js convention, fetchDinoReport passes the error to the callback first and the data second. The test then receives a done parameter and has to call it when it finishes:
function fetchDinoReport(id, callback) {
setTimeout(() => {
if (id === 'unknown') {
callback(new Error('Dinosaur not found'), null);
} else {
callback(null, { id, status: 'healthy' });
}
}, 100);
}
// Testing callback with done
test('callback returns dinosaur report', (done) => {
fetchDinoReport('REX-001', (error, report) => {
try {
expect(error).toBeNull();
expect(report.status).toBe('healthy');
done(); // Signal test completion
} catch (err) {
done(err); // Pass error to Jest
}
});
});If done is never called, the test fails once it exceeds the time limit, 5 seconds by default. The try/catch is needed because a failed expect throws an exception inside the callback, and when passed to done(err), it reaches the report as the real reason for the failure. Do not combine done with an async test, because Jest will then report an error. For new code I recommend async/await and leave done for old APIs.
Fake Timers
When code uses setTimeout, setInterval, or Date, you can control time. Waiting 30 seconds in a test is a waste of time, so jest.useFakeTimers() swaps the clocks for fake ones. Here is a function that announces an evacuation after 30 seconds:
// Function with timeout
function startEmergencyCountdown(callback) {
console.log('Evacuation in 30 seconds!');
setTimeout(() => {
callback('Evacuation started!');
}, 30000); // 30 seconds
}And this is how we test it. jest.advanceTimersByTime fast-forwards time by the given number of milliseconds, instantly. We switch fake timers on in beforeEach and off in afterEach so they do not affect other tests:
describe('Emergency System', () => {
beforeEach(() => {
jest.useFakeTimers(); // Enable fake timers
});
afterEach(() => {
jest.useRealTimers(); // Restore real timers
});
test('countdown calls callback after 30s', () => {
const callback = jest.fn();
startEmergencyCountdown(callback);
// Callback has not been called yet
expect(callback).not.toHaveBeenCalled();
// Fast-forward time by 30 seconds
jest.advanceTimersByTime(30000);
// Now the callback has been called!
expect(callback).toHaveBeenCalledWith('Evacuation started!');
});
test('countdown does not fire before time', () => {
const callback = jest.fn();
startEmergencyCountdown(callback);
// Fast-forward by 29 seconds
jest.advanceTimersByTime(29000);
expect(callback).not.toHaveBeenCalled();
// Fast-forward by one more second (30s total)
jest.advanceTimersByTime(1000);
expect(callback).toHaveBeenCalled();
});
});The second test shows that fake time is precise: after 29 seconds the callback is still waiting, and after one more second it fires. Both tests take milliseconds, not half a minute. The production code does not know that time is fake - we did not change a single line of it.
Running Pending Timers
When you do not want to count milliseconds, jest.runAllTimers() runs all pending timers at once. Important: fake timers must be switched on before the code schedules any timers, which is why jest.useFakeTimers() sits at the very start of the test:
test('runAllTimers - run all timers', () => {
jest.useFakeTimers();
const steps = [];
setTimeout(() => steps.push('step 1'), 1000);
setTimeout(() => steps.push('step 2'), 2000);
setTimeout(() => steps.push('step 3'), 5000);
// Run ALL pending timers at once
jest.runAllTimers();
expect(steps).toEqual(['step 1', 'step 2', 'step 3']);
jest.useRealTimers();
});Timers scheduled before fake timers were switched on would land in the real queue, runAllTimers would not see them, and the steps array would stay empty. Be careful with setInterval: runAllTimers also runs timers created along the way, so an interval would spin forever until Jest breaks the loop with an error. In that case use jest.runOnlyPendingTimers(), and when timers mix with promises, reach for await jest.advanceTimersByTimeAsync(ms).
In the final project, fake timers will come in handy for sensor monitoring. In the lab below you will see a simulation of DNA scanning with promises and timers.
Remember: in an asynchronous test, always wait for the result - await is the guard who will not leave the post until the DNA scan is complete.
Code for this lesson: index.js
// Testing asynchronous code
console.log("=== Jurassic Park - Asynchronous DNA Scanning ===\n");
// --- async/await in tests ---
console.log("--- async/await ---\n");
async function scanDNA(sampleId) {
// Simulating an asynchronous scan
return new Promise((resolve, reject) => {
setTimeout(() => {
if (sampleId === "INVALID") {
reject(new Error("Sample not found"));
return;
}
resolve({
species: "T-Rex",
purity: 0.95,
viable: true,
});
}, 100);
});
}
// Test async/await
async function testAsyncAwait() {
try {
const result = await scanDNA("SAMPLE-001");
console.log("[PASS] DNA scan returned:", result.species);
console.log("[PASS] Purity:", result.purity, "> 0.9?", result.purity > 0.9);
console.log("[PASS] Viable:", result.viable);
} catch (e) {
console.log("[FAIL]", e.message);
}
}
// Test reject
async function testReject() {
try {
await scanDNA("INVALID");
console.log("[FAIL] Should have thrown");
} catch (e) {
console.log("[PASS] Rejected:", e.message);
}
}
// --- Callback testing ---
console.log("--- Callbacks ---\n");
function fetchDinoReport(id, callback) {
setTimeout(() => {
if (id === "unknown") {
callback(new Error("Dinosaur not found"), null);
} else {
callback(null, { id, status: "healthy" });
}
}, 50);
}
function testCallback() {
return new Promise((resolve) => {
fetchDinoReport("REX-001", (error, report) => {
if (!error && report.status === "healthy") {
console.log("[PASS] Callback: report status =", report.status);
} else {
console.log("[FAIL] Callback failed");
}
resolve();
});
});
}
// --- Fake Timers ---
console.log("--- Fake Timers ---\n");
function demonstrateFakeTimers() {
console.log("In the real Jest:");
console.log(" jest.useFakeTimers() - switch on fake timers");
console.log(" jest.advanceTimersByTime(30000) - fast-forward by 30s");
console.log(" jest.runAllTimers() - run all timers");
console.log(" jest.useRealTimers() - restore real timers");
console.log("\nExample:");
console.log(" function startCountdown(cb) {");
console.log(" setTimeout(() => cb('GO!'), 30000);");
console.log(" }");
console.log(" ");
console.log(" test('countdown', () => {");
console.log(" jest.useFakeTimers();");
console.log(" const cb = jest.fn();");
console.log(" startCountdown(cb);");
console.log(" expect(cb).not.toHaveBeenCalled();");
console.log(" jest.advanceTimersByTime(30000);");
console.log(" expect(cb).toHaveBeenCalledWith('GO!');");
console.log(" });");
}
// --- resolves/rejects ---
console.log("--- resolves / rejects matchers ---\n");
async function demonstrateResolves() {
// resolves
const goodPromise = Promise.resolve({ status: "activated", zone: "A" });
const result = await goodPromise;
const matches = result.status === "activated" && result.zone === "A";
console.log("[" + (matches ? "PASS" : "FAIL") + "] resolves.toEqual:", JSON.stringify(result));
// rejects
const badPromise = Promise.reject(new Error("Zone ID is required"));
try {
await badPromise;
console.log("[FAIL] Should have rejected");
} catch (e) {
const matches = e.message === "Zone ID is required";
console.log("[" + (matches ? "PASS" : "FAIL") + "] rejects.toThrow:", e.message);
}
}
// Run the tests
async function runAll() {
await testAsyncAwait();
console.log("");
await testReject();
console.log("");
await testCallback();
console.log("");
await demonstrateResolves();
console.log("");
demonstrateFakeTimers();
}
runAll();Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. How do you correctly test an async function in Jest?
2. Which Jest method allows you to advance fake time by a specified number of milliseconds?
Hands-on tasks in the game
- Vertical ordering
Arrange the steps for testing an asynchronous function:
- Code editor
Write async/await tests for the analyzeDNA and cloneDinosaur functions.
- Click in order
Arrange the elements of fake timers usage in a test:
- Code editor
Use fake timers to test the park's evacuation system.