JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionstesting
PrevNext
testing
mid
integration

What is the difference between unit tests and integration tests?

integration-testing
unit-testing
test-pyramid
msw
Quick Answer

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.

Detailed Explanation

Unit Tests:

  • Test one unit in isolation
  • Mock all dependencies
  • Fast execution
  • Pinpoint exact failures
  • Many tests needed

Integration Tests:

  • Test multiple units together
  • Real or realistic dependencies
  • Slower execution
  • Catch interaction bugs
  • Fewer tests needed

Testing Pyramid:

  • Many unit tests (base)
  • Some integration tests (middle)
  • Few E2E tests (top)

When to Use Each:

  • Unit: Business logic, pure functions
  • Integration: API routes, component trees
  • E2E: Critical user flows

Code Examples

Unit test (isolated)
// 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();
});

Resources

The Testing Trophy

article

MSW Documentation

docs

Related Questions

How do you mock functions, modules, and API calls in Jest?

mid
mocking

What are E2E tests and when should you use Cypress vs Playwright?

senior
e2e
Previous
How do you test React components with React Testing Library?
Next
What is code coverage and how do you interpret coverage reports?