🟢
Updated recently
Last updated:

Quick Answer: Contract testing with Pact verifies API consumers and providers agree on data format. The consumer writes a contract, and the provider verifies it can fulfill that contract without spinning up the entire system.

What is Contract Testing?

Contract testing validates that an API provider meets consumer expectations. Unlike integration testing, it uses lightweight contracts verified independently.

Why Contract Testing for Microservices?

  • Speed: No need to run the entire cluster
  • Isolation: Each consumer-provider pair tested independently
  • Early detection: Catch breaking changes before deployment
  • Documentation: Contracts serve as living API docs

Write a Consumer Pact Test

const { Pact } = require('@pact-foundation/pact');

describe('API Consumer', () => {
  const provider = new Pact({
    consumer: 'FrontendApp',
    provider: 'UserService',
  });

  it('should return user data', async () => {
    await provider.addInteraction({
      state: 'a user exists',
      uponReceiving: 'a request for user 123',
      withRequest: { method: 'GET', path: '/users/123' },
      willRespondWith: {
        status: 200,
        body: { id: 123, name: 'John' },
      },
    });
    const response = await fetch(`${provider.mockServiceBaseUrl}/users/123`);
    const user = await response.json();
    expect(user.name).toBe('John');
  });
});

Pact vs Integration Testing

Aspect Contract Testing Integration Testing
Speed Fast (ms) Slow (sec to min)
Infrastructure Minimal Full stack
Isolation Per pair Entire system

Training Resources

Master API testing with SkilBrill API Testing Training.

FAQ

Does contract testing replace integration testing?

No. Contract testing prevents API breaking changes. Integration testing validates end-to-end business logic.