Unit tests test individual functions/components in isolation with mocked dependencies. Integration tests verify multiple units work together correctly, testing real interactions between components, APIs, or databases with fewer mocks.
Unit Tests:
Integration Tests:
Testing Pyramid:
When to Use Each:
// Unit test - pure function, no dependencies
function calculateTotal(items) {
return items.reduce((sum, item) => sum + item.price * item.quantity, 0);
}
describe('calculateTotal', () => {
test('calculates sum of items', () => {
const items = [
{ price: 10, quantity: 2 },
{ price: 5, quantity: 3 }
];
expect(calculateTotal(items)).toBe(35);
});
test('returns 0 for empty array', () => {
expect(calculateTotal([])).toBe(0);
});
});
// Unit test - component with mocked hook
jest.mock('./useUser', () => ({
useUser: () => ({ user: { name: 'Alice' }, loading: false })
}));
test('displays user name', () => {
render(<UserProfile />);
expect(screen.getByText('Alice')).toBeInTheDocument();
});