Sobes.tech
Junior — Middle

Have you ever used Pact for creating mocks in API testing?

sobes.tech AI

Answer from AI

Pact is a contract testing tool that allows creating mocks (stubs) for APIs based on agreements between services (consumer and provider). It helps ensure that the integration between services works correctly by verifying that the provider's API matches the expectations of the consumer.

Using Pact, you can describe expected requests and responses, and then use these contracts for automated testing. This is especially useful in microservices architectures where different teams develop different services.

Example of using Pact to create a mock in JavaScript tests:

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

const provider = new Pact({
  consumer: 'ConsumerService',
  provider: 'ProviderService',
  port: 1234
});

before(() => provider.setup());

after(() => provider.finalize());

it('should return the expected response', async () => {
  await provider.addInteraction({
    state: 'user exists',
    uponReceiving: 'a request to get user',
    withRequest: {
      method: 'GET',
      path: '/user/1'
    },
    willRespondWith: {
      status: 200,
      body: { id: 1, name: 'Ivan' }
    }
  });

  // call the code under test that makes the API call

  await provider.verify();
});

Thus, Pact helps create reliable mocks for APIs and guarantees that interactions between services conform to agreements.

Have you ever used Pact for creating mocks in API… - sobes.tech