Course contentsShow
← JavaScript
Lesson 2687 of 2,72354. Testing in JavaScriptFree lesson

Using Async/Await in Tests

Writing async test functions to await promises for cleaner, more readable test code.

Using Async/Await in Tests

You'll learn how to write cleaner asynchronous tests using async/await syntax instead of callbacks or raw promises.

The Problem with Earlier Approaches

While returning promises or using done() callbacks works, they can make test code harder to read—especially when you need to make multiple assertions or chain several async operations. The code starts looking nested or requires careful promise chaining.

The Async/Await Solution

Modern JavaScript's async/await lets you write asynchronous test code that looks synchronous. Simply declare your test function as async and use await before any promise-based operation. The test runner waits for the entire async function to complete before moving on.

// Clean, readable async test
test('user data loads correctly', async () => {
  const user = await fetchUser(123);
  expect(user.name).toBe('Alice');
  expect(user.active).toBe(true);
});

This reads top-to-bottom like synchronous code, but handles the asynchronous operation properly.

Multiple Async Operations

The real power shows when you need several async steps:

test('full user workflow', async () => {
  const user = await createUser({ name: 'Bob' });
  const updated = await updateUser(user.id, { active: true });
  const fetched = await fetchUser(user.id);
  
  expect(fetched.active).toBe(true);
});

No callback nesting, no promise chains—just sequential, readable code.

Error Handling

Testing rejected promises is straightforward with try-catch or assertion helpers:

test('handles missing user', async () => {
  await expect(fetchUser(999)).rejects.toThrow('User not found');
});

Key Takeaway: Using async/await in test functions produces the cleanest, most maintainable asynchronous test code—just mark your test function async and await any promises, letting the test runner handle the rest naturally.