Unit Testing vs Integration Testing
Advertisement
Ad
Unit vs Integration Testing
Both verify your code, but at different scopes. Unit tests check individual pieces in isolation; integration tests check how pieces work together.
Comparison
| Aspect | Unit | Integration |
|---|---|---|
| Scope | One function | Multiple parts |
| Speed | Very fast | Slower |
| Dependencies | Mocked | Real |
| Catches | Logic bugs | Interface bugs |
Unit Test Example
test("calculates total", () => {
expect(calculateTotal([10, 20])).toBe(30);
});
Integration Test Example
test("creates user in database", async () => {
const res = await request(app)
.post("/users")
.send({ name: "Sara" });
expect(res.status).toBe(201);
// Tests route + controller + database together
});
The Testing Pyramid
/ E2E (few)
/ Integration (some)
/____ Unit (many)
Write lots of fast unit tests, fewer integration tests, and minimal E2E tests.
FAQs
Which should I write first?
Unit tests — fast feedback while developing. More in our Testing section.
What is mocking?
Replacing real dependencies with fakes to isolate the code under test.
