Advertisement
Advanced JavaScript, Debugging, Testing & Tooling

How do you write an effective test for asynchronous code?

Short 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.

Save JavaScript mock interview
Advertisement
AModel 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.
Likely follow-ups
  • What happens if you forget the 'async' keyword on a test function that awaits something?
Related topics