Day 63

Integration Testing

11 min
JavaScript 100 Days

Integration testing mein multiple units milke test hoti hain — function A function B call karta hai, aur result test karte hain. Real API ya database ki jagah mocks use karte hain.

Testing with Mocks

API calls mock karo integration tests mein.

user-service.test.js
javascript
// user-service.js
async function getUserWithPosts(userId) {
  const user = await fetchUser(userId);
  const posts = await fetchPosts(userId);
  return { ...user, posts };
}

// test file — fetch mock karo
global.fetch = jest.fn();

describe("getUserWithPosts integration", () => {
  beforeEach(() => {
    fetch.mockClear();
  });
  
  test("returns user with their posts", async () => {
    // Mock responses in order
    fetch
      .mockResolvedValueOnce({
        ok: true,
        json: async () => ({ id: 1, name: "Zohaib" })
      })
      .mockResolvedValueOnce({
        ok: true,
        json: async () => [{ id: 1, title: "My Post" }]
      });
    
    const result = await getUserWithPosts(1);
    
    expect(result.name).toBe("Zohaib");
    expect(result.posts).toHaveLength(1);
    expect(fetch).toHaveBeenCalledTimes(2);
  });
  
  test("handles API failure gracefully", async () => {
    fetch.mockRejectedValueOnce(new Error("Network error"));
    await expect(getUserWithPosts(1)).rejects.toThrow("Network error");
  });
});

🎯 Practice Challenge

OrderService banao jo cart + payment + inventory check karta ho. Integration tests likho with mocked services.