4. Jest: Async Testing and Promise Handling
Real-world applications are full of asynchronous code. Testing async code requires different approaches than testing synchronous code. This module covers Jest's async testing features, including callbacks, promises, and async/await.
The key insight is that Jest provides multiple ways to test async code. You can use callbacks (done), promises (return), or async/await (the modern way). Understanding each approach helps you choose the right one for your use case. Async testing is essential for testing API calls, database operations, and timers.
This module covers testing promises, async/await, error handling, and timers.
Testing Callbacks with done
The done callback is the traditional way to test async code. Jest waits for the done callback to be called before finishing the test. If done is not called, the test times out. This approach works with any callback-based async code.
While done still works, it's less common now that promises and async/await are widely supported. Use done when you need to test callback-based code, but prefer async/await for new code.
Testing Promises and Async/Await
Promises are the modern way to handle async code in JavaScript. Jest supports testing promises by returning them from the test function. If the promise resolves, the test passes. If it rejects, the test fails.
Async/await is the most readable way to test async code. It makes async tests look like sync tests, improving readability. Use async/await for most async tests. Use the .resolves and .rejects matchers for simple promise assertions.
// Async function to test const fetchData = () => { return new Promise((resolve) => { setTimeout(() => resolve('data'), 100); }); }; const fetchError = () => { return new Promise((_, reject) => { setTimeout(() => reject(new Error('Failed')), 100); }); }; // Using done callback test('fetches data with done', (done) => { fetchData().then((data) => { expect(data).toBe('data'); done(); }); }); // Using promises (return) test('fetches data with promise', () => { return fetchData().then((data) => { expect(data).toBe('data'); }); }); // Using async/await test('fetches data with async/await', async () => { const data = await fetchData(); expect(data).toBe('data'); }); // Using resolves matcher test('fetches data with resolves', () => { return expect(fetchData()).resolves.toBe('data'); }); // Testing errors test('handles errors with async/await', async () => { await expect(fetchError()).rejects.toThrow('Failed'); }); // Try/catch for complex error testing test('handles errors with try/catch', async () => { try { await fetchError(); } catch (error) { expect(error.message).toBe('Failed'); } });
Testing Timers
Jest provides fake timers for testing code that uses setTimeout, setInterval, and other timer functions. Fake timers let you control time in your tests, making them faster and more reliable. Use jest.useFakeTimers() to enable fake timers, then use jest.advanceTimersByTime() to advance time.
Timer testing is essential for testing debounce, throttle, retry logic, and animations. Without fake timers, your tests would have to wait for real time to pass, making them slow.
// Function with timer const debounce = (fn, delay) => { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), delay); }; }; // Testing with fake timers test('debounces function calls', () => { jest.useFakeTimers(); const fn = jest.fn(); const debounced = debounce(fn, 1000); debounced(); debounced(); debounced(); // Fast-forward time jest.advanceTimersByTime(1000); expect(fn).toHaveBeenCalledTimes(1); jest.useRealTimers(); }); // Testing setInterval const startCounter = (onTick) => { let count = 0; const interval = setInterval(() => { count++; onTick(count); }, 1000); return () => clearInterval(interval); }; test('counter increments every second', () => { jest.useFakeTimers(); const onTick = jest.fn(); const stop = startCounter(onTick); jest.advanceTimersByTime(3000); expect(onTick).toHaveBeenCalledTimes(3); expect(onTick).toHaveBeenCalledWith(1); expect(onTick).toHaveBeenCalledWith(2); expect(onTick).toHaveBeenCalledWith(3); stop(); jest.useRealTimers(); });
Try It Yourself: Async Testing
Follow these steps to practice async testing.
Step 1: Create the code// api.js<br>export const fetchUser = async (id) => {<br> const response = await fetch(`https://api.example.com/users/${id}`);<br> if (!response.ok) {<br> throw new Error(<strong><code>Failed to fetch user);
}
return response.json();
};
export const saveUser = async (user) => {
const response = await fetch(https://api.example.com/users, {
method: POST,
body: JSON.stringify(user),
headers: { Content-Type: application/json }
});
if (!response.ok) {
throw new Error(Failed to save user);
}
return response.json();
};
export const retryOperation = async (operation, retries = 3) => {
for (let i = 0; i < retries; i++) {
try {
return await operation();
} catch (error) {
if (i === retries - 1) throw error;
await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
}
}
};
Step 2: Write the tests// api.test.js<br>import { fetchUser, saveUser, retryOperation } from <strong><code>./api;
// Mock fetch
global.fetch = jest.fn();
describe(API functions, () => {
beforeEach(() => {
jest.clearAllMocks();
});
test(fetchUser returns user data, async () => {
const mockUser = { id: 1, name: Alice };
fetch.mockResolvedValue({
ok: true,
json: jest.fn().mockResolvedValue(mockUser)
});
const result = await fetchUser(1);
expect(result).toEqual(mockUser);
expect(fetch).toHaveBeenCalledWith(https://api.example.com/users/1);
});
test(fetchUser throws on error, async () => {
fetch.mockResolvedValue({ ok: false });
await expect(fetchUser(1)).rejects.toThrow(Failed to fetch user);
});
test(saveUser saves user data, async () => {
const user = { name: Bob };
const mockResponse = { id: 2, ...user };
fetch.mockResolvedValue({
ok: true,
json: jest.fn().mockResolvedValue(mockResponse)
});
const result = await saveUser(user);
expect(result).toEqual(mockResponse);
});
test(retryOperation retries on failure, async () => {
const operation = jest.fn()
.mockRejectedValueOnce(new Error(Fail 1))
.mockRejectedValueOnce(new Error(Fail 2))
.mockResolvedValue(Success);
const result = await retryOperation(operation, 3);
expect(result).toBe(Success);
expect(operation).toHaveBeenCalledTimes(3);
});
});
Step 3: Run the testsnpx jest
Try It Yourself: Create a function that retries an operation with exponential backoff. Write tests that verify the retry behavior and the backoff timing.
Knowledge Check
Ready to test your understanding of 4. Jest: Async Testing and Promise Handling?