Package detail

jest-pact

pact-foundation135.7kMIT0.11.3

a pact adaptor for jest

readme

Jest-Pact

npm version npm TravisCI Maintainability Coverage Status Dependency Status devDependency Status

Jest Adaptor to help write Pact files with ease

Features

  • [x] instantiates the PactOptions for you
  • [x] Setups Pact mock service before and after hooks so you don’t have to
  • [x] Set Jest timeout to 30 seconds preventing brittle tests in slow environments like Docker
  • [x] Sensible defaults for the pact options that make sense with Jest
  • [x] Supports both the main release of pact-js (9.x.x) and the beta 10.x.x for Pact spec V3

Jest-Pact Roadmap

  • [ ] Ensure that jest-pact plays well with jest's default of watch-mode (This has been mothballed, please see this draft pr for details. Contributions welcome!
  • [ ] Ensure that pact failures print nice diffs (at the moment you have to go digging in the log files)
  • [ ] Add a setup hook for clearing out log and pact files

Adapter Installation

npm install --save-dev jest-pact
yarn add jest-pact --dev

If you have more than one file with pact tests for the same consumer/provider pair, you will also need to add --runInBand to your jest or react-scripts test command in your package.json. This avoids race conditions with the mock server writing to the pact file.

Usage - Pact-JS V2

Say that your API layer looks something like this:

import axios from 'axios';

const defaultBaseUrl = 'http://your-api.example.com';

export const api = (baseUrl = defaultBaseUrl) => ({
  getHealth: () =>
    axios.get(`${baseUrl}/health`).then((response) => response.data.status),
  /* other endpoints here */
});

Then your test might look like:

import { pactWith } from 'jest-pact';
import { Matchers } from '@pact-foundation/pact';
import api from 'yourCode';

pactWith({ consumer: 'MyConsumer', provider: 'MyProvider' }, provider => {
  let client;

  beforeEach(() => {
    client = api(provider.mockService.baseUrl)
  });

  describe('health endpoint', () => {
    // Here we set up the interaction that the Pact
    // mock provider will expect.
    //
    // jest-pact takes care of validating and tearing
    // down the provider for you.
    beforeEach(() => // note the implicit return.
                     // addInteraction returns a promise.
                     // If you don't want to implicitly return,
                     // you will need to `await` the result
      provider.addInteraction({
        state: "Server is healthy",
        uponReceiving: 'A request for API health',
        willRespondWith: {
          status: 200,
          body: {
            status: Matchers.like('up'),
          },
        },
        withRequest: {
          method: 'GET',
          path: '/health',
        },
      })
    );

    // You also test that the API returns the correct
    // response to the data layer.
    //
    // Although Pact will ensure that the provider
    // returned the expected object, you need to test that
    // your code receives the right object.
    //
    // This is often the same as the object that was
    // in the network response, but (as illustrated
    // here) not always.
    it('returns server health', () => // implicit return again
      client.getHealth().then(health => {
        expect(health).toEqual('up');
      }));
  });
});

Usage - Pact-JS V3

We also include a wrapper for Pact-JS V3.

Note: The API is NOT finalised. Feedback welcome

If you have thoughts or feedback about the DSL, please let us know via slack or open issue.

Currently, only a default for the pact directory is provided by the jest-pact wrapper jest-pact/dist/v3.

import { pactWith } from 'jest-pact/dist/v3';
import { MatchersV3 } from '@pact-foundation/pact';
import api from 'yourCode';

pactWith({ consumer: 'MyConsumer', provider: 'MyProvider' }, (interaction) => {
  interaction('A request for API health', ({ provider, execute }) => {
    beforeEach(() =>
      provider
        .given('Server is healthy')
        .uponReceiving('A request for API health')
        .withRequest({
          method: 'GET',
          path: '/health',
        })
        .willRespondWith({
          status: 200,
          body: {
            status: MatchersV3.like('up'),
          },
        })
    );

    execute('some api call', (mockserver) =>
      api(mockserver.url)
        .health()
        .then((health) => {
          expect(health).toEqual('up');
        })
    );
  });
});

Best practices

You can make your tests easier to read by extracting your request and responses:

/* pact.fixtures.js */
import { Matchers } from '@pact-foundation/pact';

export const healthRequest = {
  uponReceiving: 'A request for API health',
  withRequest: {
    method: 'GET',
    path: '/health',
  },
};

export const healthyResponse = {
  status: 200,
  body: {
    status: Matchers.like('up'),
  },
};
import { pactWith } from 'jest-pact';
import { healthRequest, healthyResponse } from "./pact.fixtures";

import api from 'yourCode';

pactWith({ consumer: 'MyConsumer', provider: 'MyProvider' }, provider => {
  let client;

  beforeEach(() => {
    client = api(provider.mockService.baseUrl)
  });

  describe('health endpoint', () => {

    beforeEach(() =>
      provider.addInteraction({
        state: "Server is healthy",
        ...healthRequest,
        willRespondWith: healthyResponse
      })
    );

    it('returns server health', () =>
      client.getHealth().then(health => {
        expect(health).toEqual('up');
      }));
  });

Common gotchas

  • Forgetting to wait for the promise from addInteraction in beforeEach. You can return the promise, or use async/await. If you forget this, your interaction may not be set up before the test runs.
  • Forgetting to wait for the promise of your API call in it. You can return the promise, or use async/await. If you forget this, your test may pass before the expect assertion runs, causing a potentially false success.
  • Not running jest with --runInBand. If you have multiple test files that write to the same contract, you will need this to avoid intermittent failures when writing the contract file.
  • It's a good idea to specify a different log file for each invocation of pactWith, otherwise the logs will get overwritten when other specs start. If you provide an explicit port, then the default mockserver log filename includes the port number.

API Documentation

Jest-Pact has two primary functions:

  • pactWith(JestPactOptions, (providerMock) => { /* tests go here */ }): a wrapper that sets up a pact mock provider, applies sensible default options, and applies the setup and verification hooks so you don't have to
  • messagePactWith(JestMessageConsumerOptions, (messagePact) => { /* tests go here */ }): a wrapper that sets up a message pact instance and applies sensible default options

Additionally, pactWith.only / fpactWith, pactWith.skip / xpactWith, messagePactWith.only / fmessagePactWith and messagePactWith.skip / xmessagePactWith behave as you would expect from Jest.

There are two types exported:

  • JestProvidedPactFn: This is the type of the second argument to pactWith, ie: (provider: Pact) => void
  • JestPactOptions: An extended version of PactOptions that has some additional convienience options (see below).

Configuration

You can use all the usual PactOptions from pact-js, plus a timeout for telling jest to wait a bit longer for pact to start and run.

pactWith(JestPactOptions, (provider) => {
  // regular http pact tests go here
});
messagePactWith(JestMessageConsumerOptions, (messagePact) => {
  // regular message pact tests go here
});

interface ExtraOptions {
  timeout?: number; // Timeout for pact service start/teardown, expressed in milliseconds
  // Default is 30000 milliseconds (30 seconds).
  logDir?: string; // path for the log file
  logFileName?: string; // filename for the log file
}

type JestPactOptions = PactOptions & ExtraOptions;

type JestMessageConsumerOptions = MessageConsumerOptions & ExtraOptions;

Defaults

Jest-Pact sets some helpful default PactOptions for you. You can override any of these by explicitly setting corresponding option. Here are the defaults:

  • log is set so that log files are written to /pact/logs, and named <consumer>-<provider>-mockserver-interaction.log. If you provided an explicit port, then the log file name is <consumer>-<provider>-mockserver-interaction-port-<portNumber>.log
  • dir is set so that pact files are written to /pact/pacts
  • logLevel is set to warn
  • timeout is 30,000 milliseconds (30 seconds)
  • pactfileWriteMode is set to "update"

Most of the time you won't need to change these.

A common use case for log is to change only the filename or the path for logging. To help with this, Jest-Pact provides convenience options logDir and logFileName. These allow you to set the path or the filename independently. In case you're wondering, if you specify log, logDir and logFileName, the convenience options are ignored and log takes precedence.

Jest Watch Mode

By default Jest will watch all your files for changes, which means it will run in an infinite loop as your pact tests will generate json pact files and log files.

You can get around this by using the following watchPathIgnorePatterns: ["pact/logs/*","pact/pacts/*"] in your jest.config.js

Example

module.exports = {
  testMatch: ['**/*.test.(ts|js)', '**/*.it.(ts|js)', '**/*.pacttest.(ts|js)'],
  watchPathIgnorePatterns: ['pact/logs/*', 'pact/pacts/*'],
};

You can now run your tests with jest --watch and when you change a pact file, or your source code, your pact tests will run

Examples of usage of jest-pact

See Jest-Pact-Typescript which showcases a full consumer workflow written in Typescript with Jest, using this adaptor

  • [x] Example pact tests
    • [x] AWS v4 Signed API Gateway Provider
    • [x] Soap API provider
    • [x] File upload API provider
    • [x] JSON API provider

Examples Installation

  • clone repository git@github.com:YOU54F/jest-pact-typescript.git
  • Run yarn install
  • Run yarn run pact-test

Generated pacts will be output in pact/pacts Log files will be output in pact/logs

Credits

changelog

Changelog

All notable changes to this project will be documented in this file. See standard-version for commit guidelines.

0.11.3 (2025-03-24)

Bug Fixes

  • peer-deps: update pact-js to allow 15.x (561c02c)

0.11.2 (2025-02-17)

Bug Fixes

0.11.1 (2024-06-19)

Bug Fixes

  • Open peer deps for pact-js v13 (db783ec)

0.11.0 (2023-07-11)

⚠ BREAKING CHANGES

  • require at least node 16

Features

Bug Fixes

  • require at least node 16 (5c9d7eb)

0.10.3 (2023-03-21)

Features

0.10.2 (2022-12-05)

Features

  • jest: Add jest 29 support (017abf3)

0.10.1 (2022-08-08)

Features

  • v3: Add draft withPact interface for V3 (8ba6e66)

0.9.4 (2022-05-20)

Bug Fixes

  • Add Jest@28 to the peer dependencies (and fix a few other issues) (#211) (0bd968e)

0.9.3 (2022-03-21)

Features

  • Release GH actions by removing dryRun flag (3778ee3)

0.9.2 (2022-03-21)

Bug Fixes

  • Add GH actions for release pipeline (af82206)

0.9.1 (2021-06-16)

Features

  • Mark jest-pact as compatible with jest 27 (and )move jest types to dev dependencies) (df15f75)

0.9.0 (2021-05-08)

⚠ BREAKING CHANGES

  • Increased peerdeps for @pact-foundation/pact to 9.12.2 and above

Bug Fixes

  • Fix compile error when used with @pact-foundation/pact version 9.15.0 and above (b89a114)

0.8.3 (2021-02-23)

0.8.2 (2021-02-23)

Features

  • dsl: Add pactWith.only and pactWith.skip, which behave like their describe counterparts (540dc3c)
  • messagePact: Add messagePactWith so that the default options are available for message pact users too (a8c1943)

0.8.1 (2020-08-18)

Bug Fixes

  • jest-26: Use global object to avoid 'jasmine is undefined' error (9e46c9b)

0.8.0 (2020-08-18)

Features

  • jest: Add support for Jest v26.x by using jest.setTimeout() (Fixes #197) (078f0d1)
  • options: Add convienience options logDir and logFileName (2d61354)
  • types: Add JestProvidedPactFn to improve type safety for callers of withPact (f63ce87)

Bug Fixes

  • peerDeps: Widen peer deps to include Jest v24.x.x and v25.x.x (50355e2)

0.7.0 (2020-07-18)

Features

  • dsl: Add xpactWith and fpactWith to improve the experience when skipping tests (da82056)

0.6.0 (2020-06-28)

Features

  • logs: Add port number to log file names (mitigates #193) (e8af055)

0.5.4 (2020-05-13)

Bug Fixes

  • defaults: Set LogLevel to warn by default (previously was error) (83a29eb)

0.5.3 (2020-05-05)

Bug Fixes

  • deps: update dependency @types/jest to v25.1.3 (27731ae)
  • deps: update dependency @types/jest to v25.1.4 (e601980)
  • options: fix a bug where 'dir' wouldn't take absolute paths (1cec75d)
  • options: remove PactOptions redefinition, introduce JestPactOptions (b622f01)

0.5.2 (2020-02-18)

0.5.1 (2020-02-12)

0.4.6 (2020-02-12)

Bug Fixes

  • deps: update dependency @types/jest to v24.0.20 (4c3ef1e)
  • deps: update dependency @types/jest to v24.0.22 (e56dca1)
  • deps: update dependency @types/jest to v24.0.23 (#130) (d1b54a7)
  • deps: update dependency @types/jest to v24.0.24 (53935dc)
  • deps: update dependency @types/jest to v24.0.25 (a7b1ec9)
  • deps: update dependency @types/jest to v24.9.0 (ac2f6da)
  • deps: update dependency @types/jest to v24.9.1 (0030690)
  • deps: update dependency @types/jest to v25 (#167) (49d5f69)
  • deps: update dependency @types/jest to v25.1.2 (b0862b0)

Features

  • timeout: prevent brittle tests by increasing Jasmine timeouts (51d23cf)

0.4.5 (2019-10-17)

Bug Fixes

  • deps: update dependency @types/jest to v24.0.19 (9063d84)

0.4.4 (2019-08-07)

Bug Fixes

  • deps: update dependency @types/jest to v24.0.17 (#82) (9b58ea0)

0.4.3 (2019-07-08)

Bug Fixes

  • deps: update dependency @types/jest to v24.0.15 (#66) (8798aed)

0.4.2 (2019-06-14)

Bug Fixes

  • drop peer dep on Jest to 24.7.1 to match current create-react-app (e8cc52b)

0.4.1 (2019-06-12)

Bug Fixes

  • log path when user specified is writing to file (30bbba1)

0.4.0 (2019-06-12)

Features

  • allow configuration of pacts and log dirs (c4c3b24)

0.3.0 (2019-05-31)

Features

0.2.0 (2019-05-31)

Bug Fixes

  • dependencies: Make jest and pact-node peer dependencies (99abbc1)

Features

  • options: Add pactfileWriteMode to options (6532b11)
  • expose getProviderBaseUrl (f0a1db3)

Tests

  • release v0.1.0, test locally, upload ci test results, plus moving test related files into examples (d5d9fca)

0.0.10 (2019-05-02)

0.0.9 (2019-05-01)