Back to results for “Debugging”
JavaScript › Debugging, Testing & Tooling

How do you write an effective test for asynchronous code?

Advanced

Answer

Return or await the Promise inside the test function so the test runner waits for it to resolve before checking assertions; forgetting to await causes the test to pass falsely before the async work even finishes.
test('fetches user data', async () => {
  const user = await fetchUser(1);
  expect(user.name).toBe('Sam');
});
Real-world example Testing that an async API wrapper correctly parses and returns the expected shape of data.

Common follow-ups: What happens if you forget the 'async' keyword on a test function that awaits something?