Testing Promises
Return promises or use async/await in test functions. Use jest.fn() to mock async dependencies.
Return promises or use async/await in test functions. Use jest.fn() to mock async dependencies.
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");
});
mockResolvedValue and mockRejectedValue cover the happy and error paths of async tests.
More in JavaScript