Async Test
Question
How do you test async functions in Jest?
Hint
async/await is the modern way to test async code.
Explanation
Jest supports several async testing patterns: 1) async/await — test("async", async () => { const result = await fetchData(); expect(result).toBe(42); }). 2) Return the promise — test("promise", () => { return fetchData().then(r => expect(r).toBe(42)); }). 3) Callbacks — test("cb", done => { fetchData(r => { expect(r).toBe(42); done(); }); }). async/await is preferred for readability. For rejected promises: await expect(fetchData()).rejects.toThrow("error"). Always handle async properly — unhandled promise rejections cause false positives (test passes when it should fail).
Related Resources
Related Lessons
- Async Testing
Learn async tests.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.