Open in TheBrain

2. Consumer-Side Testing

Setting up Consumer-Side Testing for PACT Testing involves creating contract tests that define the consumer's expectations of the provider. Here's how you can do it step-by-step:


1. Set Up Your Project

- Add the relevant Pact library to your project. Choose the library based on your programming language:

     - **Java**: Use Pact JVM (`pact-jvm-consumer`).
     - **JavaScript**: Install Pact JS (`@pact-foundation/pact`).
     - **Ruby**: Use the Pact Ruby gem.
     - Other languages also have Pact libraries available.

2. Initialize the Pact Object

- Set up the Pact object in your consumer test suite. This object defines the consumer and provider services involved in the contract.

Example (JavaScript):

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

const provider = new Pact({

     consumer: 'ConsumerService',
     provider: 'ProviderService',
     port: 1234, // Port where the mock provider will run
     log: './logs/pact.log',
     dir: './pacts', // Directory to save generated contracts

});

```


3. Write Consumer Tests

- Create unit tests that simulate the consumer's interactions with the provider.

- Define the requests (method, endpoint, headers, body) and the expected responses (status code, headers, body).

- Use the mock provider to test these interactions.

Example (JavaScript):

describe('Consumer Pact Test', () => {

     before(() => provider.setup());
     after(() => provider.finalize());
     it('should request data from the provider', async () => {
       await provider.addInteraction({
         state: 'Provider has data',
         uponReceiving: 'A request for user information',
         withRequest: {
           method: 'GET',
           path: '/user/123',
         },
         willRespondWith: {
           status: 200,
           headers: { 'Content-Type': 'application/json' },
           body: { id: 123, name: 'Sri', role: 'developer' },
         },
       });
       // Make the actual call from your consumer app
       // Replace `fetchData` with your actual consumer-side function
       const response = await fetchData('/user/123');
       expect(response).to.deep.equal({ id: 123, name: 'Sri', role: 'developer' });
     });

});

```


4. Generate the Pact File

- Once all tests pass, the Pact library generates a Pact file (e.g., ConsumerService-ProviderService.json).

- This file describes the interaction contract and is shared with the provider.


5. Publish the Pact File

- Use a Pact Broker to share the Pact file with the provider team.

- The Pact Broker also supports contract versioning and verification status tracking.


6. Automate the Tests

- Add the consumer-side tests to your CI/CD pipeline to ensure the Pact file is updated and validated with every change.


This setup ensures that your consumer and provider stay aligned and that any breaking changes are detected early.