How to use PactJS with Cypress?

Vikash Anand Singh
2 min readOct 10, 2023

--

Using PactJS with Cypress allows you to perform contract testing for API interactions within your Cypress tests. Pact is a contract testing tool that helps ensure that the interactions between your consumer (Cypress) and provider (API) conform to predefined contracts. Below are the steps to use PactJS with Cypress:

1. Set Up Your Project:

  • Ensure you have a Cypress project set up and configured.

2. Install Pact Libraries:

  • Install the necessary libraries for Pact:
npm install @pact-foundation/pact-node @pact-foundation/pact-web

3. Create a Pact Configuration:

  • Create a Pact configuration file (e.g., pact.config.js) to define your contract and specify the API provider.
const path = require('path');
const { Pact } = require('@pact-foundation/pact');

module.exports = {
pact: new Pact({
port: 1234, // Port for Pact's mock service
consumer: 'Your Cypress Tests', // Consumer name
provider: 'Your API Provider', // Provider name
log: path.resolve(process.cwd(), 'logs', 'pact.log'), // Pact log file
dir: path.resolve(process.cwd(), 'pacts'), // Pact contract files directory
spec: 2, // Pact specification version
}),
};

4. Write Cypress Tests with PactJS:

  • In your Cypress test files, use PactJS to define interactions and expectations.
const { Matchers } = require('@pact-foundation/pact');
const { like } = Matchers;

describe('Contract Testing with Pact', () => {
beforeEach(() => {
// Start the Pact mock service
cy.task('pact:start');
});

afterEach(() => {
// Stop the Pact mock service
cy.task('pact:stop');
});

it('should verify the contract with the API', () => {
cy.task('pact:spec', {
cors: true, // Enable CORS for the mock service
});

cy.request({
method: 'GET',
url: 'http://localhost:1234/api/data', // Use the Pact mock service URL
}).then((response) => {
// Define the expected response based on your contract
const expectedResponse = {
name: like('John Doe'),
age: like(30),
email: like('johndoe@example.com'),
};

// Assert that the response matches the contract
expect(response.status).to.equal(200); // Ensure a successful response
expect(response.body).to.deep.equal(expectedResponse);
});
});
});

5. Run Your Cypress Tests:

  • Use the Cypress Test Runner to execute your contract tests.

6. Generate Pact Contracts:

  • After running your tests, Pact will generate contract files in the specified directory (pacts in this example).

7. Verify Contracts with the Provider:

  • Share the generated contract files with your API provider.
  • The provider can use Pact to verify that their service adheres to the contract.

Using PactJS with Cypress allows you to ensure that your API interactions conform to predefined contracts, helping to prevent integration issues and maintain compatibility between consumer and provider components.

--

--

Vikash Anand Singh

Test Lead | QA Enthusiast | Driving Quality Excellence @ DXC Technology