SyntaxStudy
Sign Up
JavaScript Intermediate 4 min read

Testing Async Code

Testing Promises

Return promises or use async/await in test functions. Use jest.fn() to mock async dependencies.

Example
test("fetches user", async () => {
  global.fetch = jest.fn().mockResolvedValue({
    ok: true,
    json: async () => ({ id: 1, name: "Alice" }),
  });
  const user = await loadUser(1);
  expect(user.name).toBe("Alice");
  expect(fetch).toHaveBeenCalledWith("/api/users/1");
});
Pro Tip

mockResolvedValue and mockRejectedValue cover the happy and error paths of async tests.