JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

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

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionstesting
PrevNext

Learn the concept

Testing Asynchronous Code

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 testingJavaScript
// 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');
    }
  });
});

Real-World Applications

Use Cases

Testing a custom React hook that performs data fetching from an API

Using `async/await` with `jest-dom/extend-expect` to test the hook's behavior, ensuring it correctly handles loading states, successful data retrieval, and error conditions when interacting with asynchronous operations.

Verifying the functionality of a utility function that interacts with a message queue or a WebSocket connection

Employing promises or the `done` callback pattern to ensure that the test waits for the asynchronous message to be sent/received and then asserts on the expected state changes.

Testing a user authentication flow that involves multiple asynchronous steps (e.g., API calls, token storage)

Structuring tests with `async/await` to simulate user interactions and await the completion of each asynchronous step, asserting on UI changes and data persistence at various points in the flow.

Mini Projects

Async Data Fetching Test

intermediate

Create a simple JavaScript function that simulates fetching data from an API using `setTimeout` to mimic latency. Write Jest tests for this function using `async/await` to verify successful data retrieval and error handling.

Promise-Based Utility Test

beginner

Develop a utility function that returns a Promise. Write Jest tests that use `.resolves` and `.rejects` matchers to assert the successful resolution and error rejection of the promise.

Industry Examples

Stripe (Payments API)

Stripe's frontend SDKs and backend services deal extensively with asynchronous operations due to network requests for payment processing. Their test suites use `async/await` and promise-based assertions to rigorously test the reliability and correctness of these critical asynchronous flows.

Netflix (UI/API Interactions)

Netflix's highly dynamic user interface involves numerous asynchronous interactions, from fetching movie recommendations to handling user preferences. Their testing infrastructure heavily relies on Jest's async testing capabilities to ensure these interactions are seamless and error-free.

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?
PrevNext