Learn the concept
Integration Tests vs Unit Tests
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();
});Writing an integration test that simulates user input in the UI, mocks only the external payment gateway, and then asserts that the API receives the correct payload and the user record is created in a test database.
Developing integration tests that render the component within a real Redux provider or Context provider, dispatch actions, and assert that the component's UI updates correctly based on the shared state.
Creating integration tests that bring up a subset of the actual services, send a test message through the pipeline, and assert on the final processed output, ensuring the entire flow works as expected.
Build a React component that fetches data from an API. Write an integration test using MSW (Mock Service Worker) to mock the API and verify that the component fetches and displays the data correctly.
Create a user profile page with editable fields. Write an integration test that simulates editing the profile, saving it via an API call (mocked), and verifying the UI updates to reflect the changes.
AWS services are often tested with extensive integration tests to ensure that different components (e.g., EC2, S3, Lambda) work seamlessly together. These tests simulate real-world scenarios across multiple services to guarantee platform reliability.
Gmail, a massive web application, uses integration tests to verify that its various features like email composition, contact management, and calendar integration function correctly when combined, even if individual units work in isolation.