Jest supports testing async code with: async/await (recommended), returning Promises, or using the done callback. For async/await, mark test as async and use await. Always ensure async tests complete properly or they'll timeout.
Methods for Async Testing:
async/await (Recommended)
Returning Promises
done Callback
Testing Rejections:
expect(promise).rejects.toThrow()try/catch with expect.assertions()// Function to test
async function fetchUser(id) {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) {
throw new Error('User not found');
}
return response.json();
}
describe('fetchUser', () => {
// Async/await approach (recommended)
test('fetches user successfully', async () => {
const user = await fetchUser(1);
expect(user).toHaveProperty('name');
expect(user.id).toBe(1);
});
// Testing rejection
test('throws error for invalid user', async () => {
await expect(fetchUser(999)).rejects.toThrow('User not found');
});
// Alternative: try/catch
test('handles error with try/catch', async () => {
expect.assertions(1); // Ensure assertion runs
try {
await fetchUser(999);
} catch (error) {
expect(error.message).toBe('User not found');
}
});
});