JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionstesting
PrevNext
testing
junior
async

How do you test asynchronous code in Jest?

async
promises
await
testing
jest
Quick Answer

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.

Detailed Explanation

Methods for Async Testing:

  1. async/await (Recommended)

    • Mark test function as async
    • Await the async operation
    • Use standard expect assertions
  2. Returning Promises

    • Return the promise from test
    • Jest waits for it to resolve
  3. done Callback

    • Call done() when test completes
    • Call done(error) for failures
    • Legacy approach

Testing Rejections:

  • expect(promise).rejects.toThrow()
  • try/catch with expect.assertions()

Code Examples

Async/await testing
// 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');
    }
  });
});

Resources

Jest - Testing Asynchronous Code

docs

Related Questions

How do you mock functions, modules, and API calls in Jest?

mid
mocking
Previous
How do you use beforeEach, afterEach, beforeAll, and afterAll in Jest?
Next
How should you structure and organize test files?