Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@pact-foundation/pact-web

pact-foundation6.4kMIT9.18.1TypeScript support: included

Pact for the browser

pact, pact-js, javascript, contract testing, testing, consumer driven testing

readme

Pact JS

Build Status npm Release workflow Coverage Status Code Climate Issue Count Known Vulnerabilities license slack

Implementation of the consumer driven contract library Pact for Javascript.

From the Pact website:

The Pact family of frameworks provide support for Consumer Driven Contracts testing.

A Contract is a collection of agreements between a client (Consumer) and an API (Provider) that describes the interactions that can take place between them.

Consumer Driven Contracts is a pattern that drives the development of the Provider from its Consumers point of view.

Pact is a testing tool that guarantees those Contracts are satisfied.

Read [Getting started with Pact] for more information for beginners.

Installation

NPM

npm install --save-dev @pact-foundation/pact@latest

Yarn

yarn add --dev @pact-foundation/pact@latest
  • Ensure you install the package as devDependencies by using [--save-dev][npm-devdep]/[--dev][yarn-devdep] ;
  • Make sure the ignore-scripts option is disabled, pact uses npm scripts to download further dependencies.

Do Not Track

In order to get better statistics as to who is using Pact, we have an anonymous tracking event that triggers when Pact installs for the first time. The only things we track are your type of OS, and the version information for the package being installed. No PII data is sent as part of this request. To respect your privacy, you can disable tracking by simply adding a 'do not track' flag within your package.json file or setting the environment variable PACT_DO_NOT_TRACK=1:

{
    "name": "some-project",
    ...
    "config": {
        "pact_do_not_track": true
    },
    ...
}

See the [Changelog] for versions and their history.

Which Library/Package should I use?

TL;DR - you almost always want Pact JS.

Purpose Library Comments
Synchronous / HTTP APIs Pact JS
Asynchronous APIs Pact JS
Node.js Pact JS
Browser testing Pact Web You probably still want Pact JS. See Using Pact in non-Node environments *
Isomorphic testing Pact Web You probably still want Pact JS. See Using Pact in non-Node environments *
Publishing to Pact Broker Pact JS

* The "I need to run it in the browser" question comes up occasionally. The question is this - for your JS code to be able to make a call to another API, is this dependent on browser-specific code? In most cases, people use tools like React/Angular which have libraries that work on the server and client side, in which case, these tests don't need to run in a browser and could instead be executed in a Node.js environment.

Using Pact JS

Pact supports synchronous request-response style HTTP interactions and asynchronous interactions with JSON-formatted payloads.

HTTP API Testing

Consumer Side Testing

To use the library on your tests, add the pact dependency:

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

The Pact class provides the following high-level APIs, they are listed in the order in which they typically get called in the lifecycle of testing a consumer:

API

API Options Returns Description
new Pact(options) See constructor options below Object Creates a Mock Server test double of your Provider API. If you need multiple Providers for a scenario, you can create as many as these as you need.
setup() n/a Promise Start the Mock Server and wait for it to be available. You would normally call this only once in a beforeAll(...) type clause
addInteraction() Object Promise Register an expectation on the Mock Server, which must be called by your test case(s). You can add multiple interactions per server, and each test would normally contain one or more of these. These will be validated and written to a pact if successful.
verify() n/a Promise Verifies that all interactions specified. This should be called once per test, to ensure your expectations were correct
finalize() n/a Promise Records the interactions registered to the Mock Server into the pact file and shuts it down. You would normally call this only once in an afterAll(...) type clause.

Constructor

Parameter Required? Type Description
consumer yes string The name of the consumer
provider yes string The name of the provider
port no number The port to run the mock service on, defaults to 1234
host no string The host to run the mock service, defaults to 127.0.0.1
ssl no boolean SSL flag to identify the protocol to be used (default false, HTTP)
sslcert no string Path to SSL certificate to serve on the mock service
sslkey no string Path to SSL key to serve on the mock service
dir no string Directory to output pact files
log no string File to log to
logLevel no string Log level: one of 'trace', 'debug', 'info', 'error', 'fatal' or 'warn'
spec no number Pact specification version (defaults to 2)
cors no boolean Allow CORS OPTION requests to be accepted, defaults to false
pactfileWriteMode no string Control how the Pact files are written. Choices: 'overwrite' 'update' or 'none'. Defaults to 'overwrite'
timeout no number The time to wait for the mock server to start up in milliseconds. Defaults to 30 seconds (30000)

Example

The first step is to create a test for your API Consumer. The example below uses Mocha, and demonstrates the basic approach:

  1. Create the Pact object
  2. Start the Mock Provider that will stand in for your actual Provider
  3. Add the interactions you expect your consumer code to make when executing the tests
  4. Write your tests - the important thing here is that you test the outbound collaborating function which calls the Provider, and not just issue raw http requests to the Provider. This ensures you are testing your actual running code, just like you would in any other unit test, and that the tests will always remain up to date with what your consumer is doing.
  5. Validate the expected interactions were made between your consumer and the Mock Service
  6. Generate the pact(s)

Check out the examples folder for examples with Mocha and Jest. The example below is taken from the integration spec.

const path = require("path")
const chai = require("chai")
const { Pact } = require("@pact-foundation/pact")
const chaiAsPromised = require("chai-as-promised")
const expect = chai.expect

chai.use(chaiAsPromised)

describe("Pact", () => {
  // (1) Create the Pact object to represent your provider
  const provider = new Pact({
    consumer: "TodoApp",
    provider: "TodoService",
    port: 1234,
    log: path.resolve(process.cwd(), "logs", "pact.log"),
    dir: path.resolve(process.cwd(), "pacts"),
    logLevel: "INFO",
  })

  // this is the response you expect from your Provider
  const EXPECTED_BODY = [
    {
      id: 1,
      name: "Project 1",
      due: "2016-02-11T09:46:56.023Z",
      tasks: [
        { id: 1, name: "Do the laundry", done: true },
        { id: 2, name: "Do the dishes", done: false },
        { id: 3, name: "Do the backyard", done: false },
        { id: 4, name: "Do nothing", done: false },
      ],
    },
  ]

  const todoApp = new TodoApp()

  context("when there are a list of projects", () => {
    describe("and there is a valid user session", () => {
      before(() =>
        provider
          // (2) Start the mock server
          .setup()
          // (3) add interactions to the Mock Server, as many as required
          .then(() =>
            provider.addInteraction({
              // The 'state' field specifies a "Provider State"
              state: "i have a list of projects",
              uponReceiving: "a request for projects",
              withRequest: {
                method: "GET",
                path: "/projects",
                headers: { Accept: "application/json" },
              },
              willRespondWith: {
                status: 200,
                headers: { "Content-Type": "application/json" },
                body: EXPECTED_BODY,
              },
            })
          )
      )
    })

    // (4) write your test(s)
    it("generates a list of TODOs for the main screen", async () => {
      const projects = await todoApp.getProjects() // <- this method would make the remote http call
      expect(projects).to.be.a("array")
      expect(projects).to.have.deep.property("projects[0].id", 1)
    })

    // (5) validate the interactions you've registered and expected occurred
    // this will throw an error if it fails telling you what went wrong
    // This should be performed once per interaction test
    afterEach(() => provider.verify())
  })

  // (6) write the pact file for this consumer-provider pair,
  // and shutdown the associated mock server.
  // You should do this only _once_ per Provider you are testing,
  // and after _all_ tests have run for that suite
  after(() => provider.finalize())
})

Provider API Testing

Once you have created Pacts for your Consumer, you need to validate those Pacts against your Provider. The Verifier object provides the following API for you to do so:

API Options Returns Description
verifyProvider() See below Promise Start the Mock Server
  1. Start your local Provider service.
  2. Optionally, instrument your API with ability to configure provider states
  3. Then run the Provider side verification step
const { Verifier } = require('@pact-foundation/pact');
let opts = {
  ...
};

new Verifier(opts).verifyProvider().then(function () {
    // do something
});

Verification Options

Parameter Required? Type Description
providerBaseUrl true string Running API provider host endpoint.
pactBrokerUrl false string Base URL of the Pact Broker from which to retrieve the pacts. Required if pactUrls not given.
provider false string Name of the provider if fetching from a Broker
consumerVersionSelectors false ConsumerVersionSelector|array Using Selectors is a way we specify which pacticipants and versions we want to use when configuring verifications.
consumerVersionTags false string|array Retrieve the latest pacts with given tag(s)
providerVersionTags false string|array Tag(s) to apply to the provider application
includeWipPactsSince false string Includes pact marked as WIP since this date. String in the format %Y-%m-%d or %Y-%m-%dT%H:%M:%S.000%:z
pactUrls false array Array of local pact file paths or HTTP-based URLs. Required if not using a Pact Broker.
providerStatesSetupUrl false string Deprecated (use URL to send PUT requests to setup a given provider state
stateHandlers false object Map of "state" to a function that sets up a given provider state. See docs below for more information
requestFilter false function Function that may be used to alter the incoming request or outgoing response from the verification process. See below for use.
beforeEach false function Function to execute prior to each interaction being validated
afterEach false function Function to execute after each interaction has been validated
pactBrokerUsername false string Username for Pact Broker basic authentication
pactBrokerPassword false string Password for Pact Broker basic authentication
pactBrokerToken false string Bearer token for Pact Broker authentication
publishVerificationResult false boolean Publish verification result to Broker (NOTE: you should only enable this during CI builds)
customProviderHeaders false array Header(s) to add to provider state set up and pact verification
providerVersion false string Provider version, required to publish verification result to Broker. Optional otherwise.
enablePending false boolean Enable the pending pacts feature.
timeout false number The duration in ms we should wait to confirm verification process was successful. Defaults to 30000.
format false string What format the verification results are printed in. Options are json, xml, progress and RspecJunitFormatter (which is a synonym for xml)
verbose false boolean Enables verbose output for underlying pact binary.

To dynamically retrieve pacts from a Pact Broker for a provider, provide the broker URL, the name of the provider, and the consumer version tags that you want to verify:

let opts = {
  pactBroker: "http://my-broker",
  provider: "Animal Profile Service",
  consumerVersionTags: ["master", "test", "prod"],
}

To verify a pact at a specific URL (eg. when running a pact verification triggered by a 'contract content changed' webhook, or when verifying a pact from your local machine, or a network location that's not the Pact Broker, set just the pactUrls, eg:

let opts = {
  pactUrls: [process.env.PACT_URL],
}

To publish the verification results back to the Pact Broker, you need to enable the 'publish' flag, set the provider version and optional provider version tags:

let opts = {
  publishVerificationResult: true, //generally you'd do something like `process.env.CI === 'true'`
  providerVersion: "version", //recommended to be the git sha
  providerVersionTags: ["tag"], //optional, recommended to be the git branch
}

If your broker has a self signed certificate, set the environment variable SSL_CERT_FILE (or SSL_CERT_DIR) pointing to a copy of your certificate.

Read more about Verifying Pacts.

API with Provider States

If you have defined any states in your consumer tests, the Verifier can put the provider into the right state prior to sending the request. For example, the provider can use the state to mock away certain database queries. To support this, set up a handler for each state using hooks on the stateHandlers property. Here is an example from our e2e suite:

const opts = {
  ...
  stateHandlers: {
    [null]: () => {
      // This is the "default" state handler, when no state is given
    }
    "Has no animals": () => {
      animalRepository.clear()
      return Promise.resolve(`Animals removed from the db`)
    },
    "Has some animals": () => {
      importData()
      return Promise.resolve(`Animals added to the db`)
    },
    "Has an animal with ID 1": () => {
      importData()
      return Promise.resolve(`Animals added to the db`)
    }
  }
}

return new Verifier(opts).verifyProvider().then(...)

As you can see, for each state ("Has no animals", ...), we configure the local datastore differently. If this option is not configured, the Verifier will ignore the provider states defined in the pact and log a warning.

Read more about Provider States.

Before and After Hooks

Sometimes, it's useful to be able to do things before or after a test has run, such as reset a database, log a metric etc. A beforeEach hook runs on each verification before any other part of the Pact test lifecycle, and a afterEach hook runs as the last step before returning the verification result back to the test.

You can add them to your verification options as follows:

const opts = {
  ...
  beforeEach: () => {
    console.log('I run before everything else')
  },

  afterEach: () => {
    console.log('I run after everything else has finished')
  }
}

If the hook errors, the test will fail. See the lifecycle of an interaction below.

Pending Pacts

NOTE: This feature is available on [Pactflow] by default, and requires configuration if using a self-hosted broker.

Pending pacts is a feature that allows consumers to publish new contracts or changes to existing contracts without breaking Provider's builds. It does so by flagging the contract as "unverified" in the Pact Broker the first time a contract is published. A Provider can then enable a behaviour (via enablePending: true) that will still perform a verification (and thus share the results back to the broker) but not fail the verification step itself.

This enables safe introduction of new contracts into the system, without breaking Provider builds, whilst still providing feedback to Consumers as per before.

See the docs and this article for more background.

WIP Pacts

NOTE: This feature is available on [Pactflow] by default, and requires configuration if using a self-hosted broker.

WIP Pacts builds upon pending pacts, enabling provider tests to pull in any contracts applicable to the provider regardless of the tag it was given. This is useful, because often times consumers won't follow the exact same tagging convention and so their workflow would be interrupted. This feature enables any pacts determined to be "work in progress" to be verified by the Provider, without causing a build failure. You can enable this behaviour by specifying a valid timestamp for includeWipPactsSince. This sets the start window for which new WIP pacts will be pulled down for verification, regardless of the tag.

See the docs and this article for more background.

Verifying multiple contracts with the same tag (e.g. for Mobile use cases)

Tags may be used to indicate a particular version of an application has been deployed to an environment - e.g. prod, and are critical in configuring can-i-deploy checks for CI/CD pipelines. In the majority of cases, only one version of an application is deployed to an environment at a time. For example, an API and a Website are usually deployed in replacement of an existing system, and any transition period is quite short lived.

Mobile is an exception to this rule - it is common to have multiple versions of an application that are in "production" simultaneously. To support this workflow, we have a feature known as consumer version selectors. Using selectors, we can verify that all pacts with a given tag should be verified. The following selectors ask the broker to "find all pacts with tag 'prod' and the latest pact for 'master'":

consumerVersionSelectors: [
  {
    tag: "prod",
    all: true,
  },
  {
    tag: "master",
    latest: true,
  },
]

NOTE: Using the all flag requires you to ensure you delete any tags associated with application versions that are no longer in production (e.g. if decommissioned from the app store)

Modify Requests Prior to Verification (Request Filters)

Sometimes you may need to add things to the requests that can't be persisted in a pact file. Examples of these are authentication tokens with a small life span. e.g. an OAuth bearer token: Authorization: Bearer 0b79bab50daca910b000d4f1a2b675d604257e42.

For these cases, we have two facilities that should be carefully used during verification:

  1. the ability to specify custom headers to be sent during provider verification. The flag to achieve this is customProviderHeaders.
  2. the ability to modify a request/response and modify the payload. The flag to achieve this is requestFilter.

Example API with Authorization

For example, to have an Authorization bearer token header sent as part of the verification request, set the verifyProvider options as per below:

let token
let opts = {
  provider: 'Animal Profile Service',
  ...
  stateHandlers: {
    "is authenticated": () => {
      token = "1234"
      Promise.resolve(`Valid bearer token generated`)
    },
    "is not authenticated": () => {
      token = ""
      Promise.resolve(`Expired bearer token generated`)
    }
  },

  // this middleware is executed for each request, allowing `token` to change between invocations
  // it is common to pair this with `stateHandlers` as per above, that can set/expire the token
  // for different test cases
  requestFilter: (req, res, next) => {
    req.headers["Authorization"] = `Bearer: ${token}`
    next()
  },

  // This header will always be sent for each and every request, and can't be dynamic
  // (i.e. passing a variable instead of the bearer token)
  customProviderHeaders: ["Authorization: Bearer 1234"]
}

return new Verifier(opts).verifyProvider().then(...)

As you can see, this is your opportunity to modify\add to headers being sent to the Provider API, for example to create a valid time-bound token.

Important Note: You should only use this feature for things that can not be persisted in the pact file. By modifying the request, you are potentially modifying the contract from the consumer tests!

Lifecycle of a provider verification

For each interaction in a pact file, the order of execution is as follows:

BeforeEach -> State Handler -> Request Filter (request phase) -> Execute Provider Test -> Request Filter (response phase) -> AfterEach

If any of the middleware or hooks fail, the tests will also fail.

Publishing Pacts to a Broker

Sharing is caring - to simplify sharing Pacts between Consumers and Providers, we have created the Pact Broker.

The Broker:

  • versions your contracts
  • tells you which versions of your applications can be deployed safely together
  • allows you to deploy your services independently
  • provides API documentation of your applications that is guaranteed to be up-to date
  • visualises the relationships between your services
  • integrates with other systems, such as Slack or your CI server, via webhooks
  • ...and much much more.

Host your own, or signup for a free hosted Pact Broker.

Publish in npm scripts

The easiest way to publish pacts to the broker is via an npm script in your package.json:


   "pact:publish": "pact-broker publish <YOUR_PACT_FILES_OR_DIR> --consumer-app-version=\"$(npx absolute-version)\" --auto-detect-version-properties --broker-base-url=https://your-broker-url.example.com"

For a full list of the options, see the CLI usage instructions. All CLI binaries are available in npm scripts when using pact-js.

If you want to pass your username and password to the broker without including them in scripts, you can provide it via the environment variables PACT_BROKER_USERNAME and PACT_BROKER_PASSWORD. If your broker supports an access token instead of a password, use the environment variable PACT_BROKER_TOKEN.

Publish in a custom script

If you require finer control over your pact publication, you can programatically publish in a custom script:

const { Publisher } = require("@pact-foundation/pact")
const opts = {
   ...
};

new Publisher(opts)
  .publishPacts()
  .then(() => {
    // ...
  })

Pact publishing options

Parameter Required Type Description
providerBaseUrl false string Running API provider host endpoint.
pactFilesOrDirs true array of strings Array of local Pact files or directories containing pact files. Path must be absolute. Required.
pactBroker true string The base URL of the Pact Broker. eg. https://test.pactflow.io. Required.
pactBrokerToken false string Bearer token for Pact Broker authentication. Optional. If using Pactflow, you likely need this option
pactBrokerUsername false string Username for Pact Broker basic authentication. Optional. If using Pactflow, you most likely need to use pactBrokerToken
pactBrokerPassword false string Password for Pact Broker basic authentication. Optional. If using Pactflow, you most likely need to use pactBrokerToken
consumerVersion true string The consumer application version; e.g. '1.0.0-cac389f'. (See more info on versioning)
tags false array of strings Tag your pacts, often used with your branching, release or environment strategy e.g. ['prod', 'test']

If your broker has a self signed certificate, set the environment variable SSL_CERT_FILE (or SSL_CERT_DIR) pointing to a copy of your certificate.

Publishing Verification Results to a Pact Broker

If you're using a Pact Broker (e.g. a hosted one at https://pactflow.io), you can publish your verification results so that consumers can query if they are safe to release.

It looks like this:

screenshot of verification result

To publish the verification results back to the Pact Broker, you need to enable the 'publish' flag, set the provider version and optional provider version tags:

let opts = {
  publishVerificationResult: true, //recommended to only publish from CI by setting the value to `process.env.CI === 'true'`
  providerVersion: "version", //recommended to be the git sha eg. process.env.MY_CI_COMMIT
  providerVersionTags: ["tag"], //optional, recommended to be the git branch eg. process.env.MY_CI_BRANCH
}

Asynchronous API Testing

Since version v6.0.0 or later

Modern distributed architectures are increasingly integrated in a decoupled, asynchronous fashion. Message queues such as ActiveMQ, RabbitMQ, SQS, Kafka and Kinesis are common, often integrated via small and frequent numbers of microservices (e.g. lambda.).

Furthermore, the web has things like WebSockets which involve bidirectional messaging.

Pact supports these use cases, by abstracting away the protocol and focussing on the messages passing between them.

For further reading and introduction into this topic, see this article and our asynchronous examples for a more detailed overview of these concepts.

Consumer

A Consumer is the system that will be reading a message from a queue or some other intermediary - like a DynamoDB table or S3 bucket - and be able to handle it.

From a Pact testing point of view, Pact takes the place of the intermediary (MQ/broker etc.) and confirms whether or not the consumer is able to handle a request.

The following test creates a contract for a Dog API handler:

const path = require("path")
const {
  MessageConsumerPact,
  synchronousBodyHandler,
} = require("@pact-foundation/pact")

// 1 Dog API Handler
const dogApiHandler = function (dog) {
  if (!dog.id && !dog.name && !dog.type) {
    throw new Error("missing fields")
  }

  // do some other things to dog...
  // e.g. dogRepository.save(dog)
  return
}

// 2 Pact Message Consumer
const messagePact = new MessageConsumerPact({
  consumer: "MyJSMessageConsumer",
  dir: path.resolve(process.cwd(), "pacts"),
  pactfileWriteMode: "update",
  provider: "MyJSMessageProvider",
})

describe("receive dog event", () => {
  it("accepts a valid dog", () => {
    // 3 Consumer expectations
    return (
      messagePact
        .given("some state")
        .expectsToReceive("a request for a dog")
        .withContent({
          id: like(1),
          name: like("rover"),
          type: term({ generate: "bulldog", matcher: "^(bulldog|sheepdog)$" }),
        })
        .withMetadata({
          "content-type": "application/json",
        })

        // 4 Verify consumers' ability to handle messages
        .verify(synchronousBodyHandler(dogApiHandler))
    )
  })
})

Explanation:

  1. The Dog API - a contrived API handler example. Expects a dog object and throws an Error if it can't handle it.
    • In most applications, some form of transactionality exists and communication with a MQ/broker happens.
    • It's important we separate out the protocol bits from the message handling bits, so that we can test that in isolation.
  2. Creates the MessageConsumer class
  3. Setup the expectations for the consumer - here we expect a dog object with three fields
  4. Pact will send the message to your message handler. If the handler returns a successful promise, the message is saved, otherwise the test fails. There are a few key things to consider:
    • The actual request body that Pact will send, will be contained within a Message object along with other context, so the body must be retrieved via content attribute.
    • All handlers to be tested must be of the shape (m: Message) => Promise<any> - that is, they must accept a Message and return a Promise. This is how we get around all of the various protocols, and will often require a lightweight adapter function to convert it.
    • In this case, we wrap the actual dogApiHandler with a convenience function synchronousBodyHandler provided by Pact, which Promisifies the handler and extracts the contents.

Provider (Producer)

A Provider (Producer in messaging parlance) is the system that will be putting a message onto the queue.

As per the Consumer case, Pact takes the position of the intermediary (MQ/broker) and checks to see whether or not the Provider sends a message that matches the Consumer's expectations.

const path = require("path")
const { MessageProviderPact } = require("@pact-foundation/pact")

// 1 Messaging integration client
const dogApiClient = {
  createDog: () => {
    return new Promise((resolve, reject) => {
      resolve({
        id: 1,
        name: "fido",
        type: "bulldog",
      })
    })
  },
}

describe("Message provider tests", () => {
  // 2 Pact setup
  const p = new MessageProviderPact({
    messageProviders: {
      "a request for a dog": () => dogApiClient.createDog(),
    },
    provider: "MyJSMessageProvider",
    providerVersion: "1.0.0",
    pactUrls: [
      path.resolve(
        process.cwd(),
        "pacts",
        "myjsmessageconsumer-myjsmessageprovider.json"
      ),
    ],
  })

  // 3 Verify the interactions
  describe("Dog API Client", () => {
    it("sends some dogs", () => {
      return p.verify()
    })
  })
})

Explanation:

  1. Our API client contains a single function createDog which is responsible for generating the message that will be sent to the consumer via some message queue
  2. We configure Pact to stand-in for the queue. The most important bit here is the messageProviders block
    • Similar to the Consumer tests, we map the various interactions that are going to be verified as denoted by their description field. In this case, a request for a dog, maps to the createDog handler. Notice how this matches the original Consumer test.
  3. We can now run the verification process. Pact will read all of the interactions specified by its consumer, and invoke each function that is responsible for generating that message.

Pact Broker Integration

As per HTTP APIs, you can publish contracts and verification results to a Broker.

Matching

Matching makes your tests more expressive making your tests less brittle.

Rather than use hard-coded values which must then be present on the Provider side, you can use regular expressions and type matches on objects and arrays to validate the structure of your APIs.

NOTE: Make sure to start the mock service via the Pact declaration with the option specification: 2 to get access to these features.

Match common formats

Often times, you find yourself having to re-write regular expressions for common formats. We've created a number of them for you to save you the time:

method description
boolean Match a boolean value (using equality)
string Match a string value
integer Will match all numbers that are integers (both ints and longs)
decimal Will match all real numbers (floating point and decimal)
hexadecimal Will match all hexadecimal encoded strings
iso8601Date Will match string containing basic ISO8601 dates (e.g. 2016-01-01)
iso8601DateTime Will match string containing ISO 8601 formatted dates (e.g. 2015-08-06T16:53:10+01:00)
iso8601DateTimeWithMillis Will match string containing ISO 8601 formatted dates, enforcing millisecond precision (e.g. 2015-08-06T16:53:10.123+01:00)
rfc3339Timestamp Will match a string containing an RFC3339 formatted timestapm (e.g. Mon, 31 Oct 2016 15:21:41 -0400)
iso8601Time Will match string containing times (e.g. T22:44:30.652Z)
ipv4Address Will match string containing IP4 formatted address
ipv6Address Will match string containing IP6 formatted address
uuid Will match strings containing UUIDs
email Will match strings containing Email address

Match based on type

const { like, string } = Matchers

provider.addInteraction({
  state: "Has some animals",
  uponReceiving: "a request for an animal",
  withRequest: {
    method: "GET",
    path: "/animals/1",
  },
  willRespondWith: {
    status: 200,
    headers: {
      "Content-Type": "application/json; charset=utf-8",
    },
    body: {
      id: 1,
      name: string("Billy"),
      address: like({
        street: "123 Smith St",
        suburb: "Smithsville",
        postcode: 7777,
      }),
    },
  },
})

Note that you can wrap a like around a single value or an object. When wrapped around an object, all values and child object values will be matched according to types, unless overridden by something more specific like a term.

Match based on arrays

Matching provides the ability to specify flexible length arrays. For example:

pact.eachLike(obj, { min: 3 })

Where obj can be any javascript object, value or Pact.Match. It takes optional argument ({ min: 3 }) where min is greater than 0 and defaults to 1 if not provided.

Below is an example that uses all of the Pact Matchers.

const { somethingLike: like, term, eachLike } = pact

const animalBodyExpectation = {
  id: 1,
  first_name: "Billy",
  last_name: "Goat",
  animal: "goat",
  age: 21,
  gender: term({
    matcher: "F|M",
    generate: "M",
  }),
  location: {
    description: "Melbourne Zoo",
    country: "Australia",
    post_code: 3000,
  },
  eligibility: {
    available: true,
    previously_married: false,
  },
  children: eachLike({ name: "Sally", age: 2 }),
}

// Define animal list payload, reusing existing object matcher
// Note that using eachLike ensure that all values are matched by type
const animalListExpectation = eachLike(animalBodyExpectation, {
  min: MIN_ANIMALS,
})

provider.addInteraction({
  state: "Has some animals",
  uponReceiving: "a request for all animals",
  withRequest: {
    method: "GET",
    path: "/animals/available",
  },
  willRespondWith: {
    status: 200,
    headers: {
      "Content-Type": "application/json; charset=utf-8",
    },
    body: animalListExpectation,
  },
})

Match by regular expression

If none of the above matchers or formats work, you can write your own regex matcher.

The underlying mock service is written in Ruby, so the regular expression must be in a Ruby format, not a Javascript format.

const { term } = pact

provider.addInteraction({
  state: "Has some animals",
  uponReceiving: "a request for an animal",
  withRequest: {
    method: "GET",
    path: "/animals/1",
  },
  willRespondWith: {
    status: 200,
    headers: {
      "Content-Type": "application/json; charset=utf-8",
    },
    body: {
      id: 100,
      name: "billy",
      gender: term({
        matcher: "F|M",
        generate: "F",
      }),
    },
  },
})

GraphQL API

GraphQL is simply an abstraction over HTTP and may be tested via Pact. There are two wrapper APIs available for GraphQL specific testing: GraphQLInteraction and ApolloGraphQLInteraction.

These are both lightweight wrappers over the standard DSL in order to make GraphQL testing a bit nicer.

See the history, and below for an example.

Tutorial (60 minutes)

Learn everything in Pact JS in 60 minutes: https://github.com/pact-foundation/pact-workshop-js.

The workshop takes you through all of the key concepts using a React consumer and an Express API.

Examples

HTTP APIs

Asynchronous APIs

Using Pact in non-Node environments such as Karma

Pact requires a Node runtime to be able to start and stop Mock servers, write logs and other things.

However, when used within browser or non-Node based environments - such as with Karma or ng-test - this is not possible.

You will need a Node based test framework such as Jest or Mocha.

Pact JS V3

An initial beta version of Pact-JS with support for V3 specification features and XML matching has been released. Current support is for Node 10, 12 and 14. Thanks to the folks at Align Tech for sponsoring this work.

To install it:

NPM

npm install --save-dev @pact-foundation/pact@beta

Yarn

yarn add --dev @pact-foundation/pact@beta
  • Ensure you install the package as devDependencies by using [--save-dev][npm-devdep]/[--dev][yarn-devdep] ;
  • Make sure the ignore-scripts option is disabled, pact uses npm scripts to download further dependencies.
  • For examples on how to use it, see examples/v3/e2e and examples/v3/todo-consumer in the v3.0.0 branch.

NOTE: The API of this implementation is likely to change. See this discussion for more

Using the V3 matching rules

There are a number of new matchers that can be used, like integer and timestamp. There are defined in the MatchersV3 class that needs to be used with PactV3 DSL.

For example:

const { PactV3, MatchersV3 } = require("@pact-foundation/pact/v3")
const {
  eachLike,
  atLeastLike,
  integer,
  timestamp,
  boolean,
  string,
  regex,
  like,
} = MatchersV3

const animalBodyExpectation = {
  id: integer(1),
  available_from: timestamp("yyyy-MM-dd'T'HH:mm:ss.SSSX"),
  first_name: string("Billy"),
  last_name: string("Goat"),
  animal: string("goat"),
  age: integer(21),
  gender: regex("F|M", "M"),
  location: {
    description: string("Melbourne Zoo"),
    country: string("Australia"),
    post_code: integer(3000),
  },
  eligibility: {
    available: boolean(true),
    previously_married: boolean(false),
  },
  interests: eachLike("walks in the garden/meadow"),
}
Matcher Parameters Description
like template Applies the type matcher to value, which requires values to have the same type as the template
eachLike template Applies the type matcher to each value in an array, ensuring they match the template. Note that this matcher does not validate the length of the array, and the items within it
atLeastOneLike template, count: number = 1 Behaves like the eachLike matcher, but also applies a minimum length validation of one on the length of the array. The optional count parameter controls the number of examples generated.
atLeastLike template, min: number, count?: number Just like atLeastOneLike, but the minimum length is configurable.
atMostLike template, max: number, count?: number Behaves like the eachLike matcher, but also applies a maximum length validation on the length of the array. The optional count parameter controls the number of examples generated.
constrainedArrayLike template, min: number, max: number, count?: number Behaves like the eachLike matcher, but also applies a minimum and maximum length validation on the length of the array. The optional count parameter controls the number of examples generated.
boolean example: boolean Matches boolean values (true, false)
integer example?: number Value that must be an integer (must be a number and have no decimal places). If the example value is omitted, a V3 Random number generator will be used.
decimal example?: number Value that must be a decimal number (must be a number and have at least one digit in the decimal places). If the example value is omitted, a V3 Random number generator will be used.
number example?: number Value that must be a number. If the example value is omitted, a V3 Random number generator will be used.
string example: string Value that must be a string.
regex pattern, example: string Value that must match the given regular expression.
equal example Value that must be equal to the example. This is mainly used to reset the matching rules which cascade.
timestamp format: string, example?: string String value that must match the provided datetime format string. See Java SimpleDateFormat for details on the format string. If the example value is omitted, a value will be generated using a Timestamp generator and the current system date and time.
time format: string, example?: string String value that must match the provided time format string. See Java SimpleDateFormat for details on the format string. If the example value is omitted, a value will be generated using a Time generator and the current system time.
date format: string, example?: string String value that must match the provided date format string. See Java SimpleDateFormat for details on the format string. If the example value is omitted, a value will be generated using a Date generator and the current system date.
includes value: string Value that must include the example value as a substring.
nullValue | Value that must be null. This will only match the JSON Null value. For other content types, it will match if the attribute is missing.

Using Pact with XML

You can write both consumer and provider verification tests with XML requests or responses. For an example, see examples/v3/todo-consumer/test/consumer.spec.js. There is an XmlBuilder class that provides a DSL to help construct XML bodies with matching rules and generators (NOTE that generators are not supported for XML at this time).

for example:

body: new XmlBuilder("1.0", "UTF-8", "ns1:projects").build((el) => {
  el.setAttributes({
    id: "1234",
    "xmlns:ns1": "http://some.namespace/and/more/stuff",
  })
  el.eachLike(
    "ns1:project",
    {
      id: integer(1),
      type: "activity",
      name: string("Project 1"),
      due: timestamp("yyyy-MM-dd'T'HH:mm:ss.SZ", "2016-02-11T09:46:56.023Z"),
    },
    (project) => {
      project.appendElement("ns1:tasks", {}, (task) => {
        task.eachLike(
          "ns1:task",
          {
            id: integer(1),
            name: string("Task 1"),
            done: boolean(true),
          },
          null,
          { examples: 5 }
        )
      })
    },
    { examples: 2 }
  )
})

Verifying providers with VerifierV3

The VerifierV3 class can verify your provider in a similar way to the existing one.

Request Filters

Request filters now take a request object as a parameter, and need to return the mutated one.

`javascript requestFilter: req => { req.headers["MY_SPECIAL_HEADER"] = "my special value"

// e.g. ADD Bearer token
req.headers["authorization"] = `Bearer ${token}`

// Need to return the request ba

changelog

Changelog

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

9.18.1 (2022-06-28)

Fixes and Improvements

  • package.json & package-lock.json to reduce vulnerabilities (#879) (5005463)

9.18.0 (2022-06-26)

Features

  • drop support for pact web incl. karma examples (d45f898)
  • modify request body inside of verifer (#873) (be8ed15)

Fixes and Improvements

  • nestjs example should use branches in workflow (a7adf07)
  • webpack on node 16 (903cf44)

9.17.3 (2022-03-16)

Fixes and Improvements

  • remove rust from v3 release build (2a5f65b)
  • The table on README.md is corrupted and unreadable (#832) (b73fa05)
  • throw an error when pact spec version is not set to 2 (4186c22)
  • upgrade to latest pact-node (0d9b127)
  • verifier req/res logging on debug (#835) (3edc5a0)

9.17.2 (2022-01-12)

Fixes and Improvements

  • All options are now passed down to pact-core in consumer pacts, allowing usage of the undocumented monkeypatch option (50f00b4)

9.17.1 (2021-12-31)

Fixes and Improvements

  • Interaction response status can only be a number not a Matcher (Typescript type) (9904eca)

9.17.0 (2021-11-19)

Features

  • upgrade pact-node to support branches in verifications. Fixes #750 (a5ef42e)

9.16.5 (2021-10-24)

Fixes and Improvements

  • Bump version of pact-node to ensure the fix for the SSL certificate issue is included (20bbf7a)
  • consumer-tests: Further improve the error message when a consumer test doesn't seem to have the mock server running (c2d789c)

9.16.4 (2021-10-10)

Fixes and Improvements

  • support null values in matchers (5bee9fc)

9.16.3 (2021-10-01)

Fixes and Improvements

  • pact-node: bump dependency on pact-node (2ab2478)

9.16.2 (2021-09-30)

Fixes and Improvements

  • give up on node 16 musl until we can remove neon (d2e2a7c)
  • Remove unused package (fixes #752) (35584fb)

9.16.1 (2021-09-08)

Fixes and Improvements

  • Add timeout option to PactOptions for waiting for the mock server to start (85c1d36)
  • bump dependency on pact-node to avoid broken 10.13.6 (de5db6b)
  • Bump version of pact-node to pick up less vulnerable dependencies (0ab095e)
  • update examples with path dependency (#717) (7c91c33)

9.16.0 (2021-06-21)

Features

  • add withMutation alias for withQuery for graphql interactions (1564a76)

Fixes and Improvements

  • Print a much better error when the mock service fails to start (bbbc6f2)

9.15.5 (2021-04-21)

Fixes and Improvements

  • pact-node: Fix for #635 (issue with message pact not respecting matching rules) (5063b7e)

9.15.4 (2021-03-31)

Fixes and Improvements

  • Bump pact-node version to get vulnerability fixes (bc0e7f0)

9.15.3 (2021-03-10)

Fixes and Improvements

  • pact-web-types: Fix issue where typescript types were not exposed in pact-web (d529082)

9.15.2 (2021-02-28)

Fixes and Improvements

  • pact-node: bump dependency on pact-node to fix regression in underlying pact broker interface (a200414)

9.15.1 (2021-02-23)

Fixes and Improvements

  • package.json & package-lock.json to reduce vulnerabilities (aa8036c)

9.15.0 (2021-02-02)

Features

  • provider-states: Add beforeEach and afterEach hooks to provider verification (#529) - Fixes #526 (8147042)

Fixes and Improvements

  • logger: lowercase log level (8388776)
  • logger: replace bunyan with pino (fe6dd30)

9.14.2 (2021-01-28)

Fixes and Improvements

  • pact-node: Bump dependency on pact-node to avoid regression in query string matching (9c733ce)
  • pact-node: bump dependency on pact-node to get verbose logging in verification #583 (66e9dca)

9.14.1 (2021-01-27)

Fixes and Improvements

  • set permissions for Ruby binaries on GH Actions (8881ee7)
  • set permissions for Ruby binaries on GH Actions (5701c0f)
  • pact-node: bump dependency on pact-node to get verbose logging in verification #583 (8b26262)
  • increase provider test timeout (f850859)
  • publish V3 was not kicking off the native libs release process (23bd533)

9.14.0 (2021-01-09)

Features

  • add request/response tracing (37c3dc3)

Fixes and Improvements

  • logger: Message consumers now respect the specified log level (98e601c)
  • pact-web: Pact-web is now built using webpack 4. Please let us know if there are any issues (27fd1b5)

9.13.2 (2021-01-04)

Bug Fixes

  • popsicle: Increase maxBufferSize of requests to infinity (8fd751a)
  • web: Use latest can-i-use database when producing distribution (cae3ea2)
  • small errors (076549e)

9.13.1 (2020-12-11)

Bug Fixes

  • Expect at least one millisecond digit in iso8601DateTimeWithMillis (4f48823)

9.13.0 (2020-10-23)

Features

  • allow WebDav REPORT request (2928613)

9.12.2 (2020-10-06)

Bug Fixes

  • types: Export LogLevel, PactOptions and MessageProviderOptions at the root of @pact-foundation/pact (a6b50d3)

9.12.1 (2020-09-24)

Bug Fixes

  • allow matcher as the top-level value of a query string (2922f8f), closes #510

9.12.0 (2020-09-21)

Features

  • allow also WebDAV HTTP Requests (2ac811d)

Bug Fixes

  • package.json & package-lock.json to reduce vulnerabilities (0bb8512)
  • pact-node: Bump version of pact-node to pick up improved logging options (1e09e1e)

9.11.1 (2020-07-18)

Bug Fixes

  • deps: Bump lodash dependency version to obtain security fix (c035482)
  • package.json & package-lock.json to reduce vulnerabilities (f147ad2)
  • package.json & package-lock.json to reduce vulnerabilities (c620dc1)
  • deps: Update vulnerable dependencies (2b2ce6e)

9.11.0 (2020-05-20)

Features

  • error thrown when query not string (c3ff00f)
  • support array as query param (d140d0c)
  • support arrays (57288ff)
  • validate object values are strings (3863527)

Bug Fixes

  • dsl: Fix extractPayload so that it passes through object properties that are not matchers (fixes #454) (c0f3d37)
  • package.json & package-lock.json to reduce vulnerabilities (69d97e0)
  • package.json & package-lock.json to reduce vulnerabilities (2184a5d)

9.10.0 (2020-04-24)

Features

  • remove need for pact-node in almost all uses, including examples (4e22828)
  • update PactWeb and MessageProviderPact interface (b82976f)

9.9.12 (2020-04-19)

9.9.11 (2020-04-19)

9.9.10 (2020-04-19)

9.9.9 (2020-04-19)

9.9.8 (2020-04-19)

9.9.7 (2020-04-19)

9.9.6 (2020-04-19)

9.9.5 (2020-04-16)

9.9.4 (2020-04-16)

9.9.3 (2020-04-10)

Bug Fixes

  • build: travis formatting (41afa50)
  • pact-node: Bump dependency on pact-node to get support for wip pacts (5e165fb)

9.9.3 (2020-04-10)

Bug Fixes

  • build: travis formatting (41afa50)
  • pact-node: Bump dependency on pact-node to get support for wip pacts (5e165fb)

9.9.3 (2020-04-10)

Bug Fixes

  • build: travis formatting (41afa50)
  • pact-node: Bump dependency on pact-node to get support for wip pacts (5e165fb)

9.9.2 (2020-03-30)

9.9.1 (2020-03-30)

9.9.0 (2020-03-26)

Features

  • support pending pacts and version selectors (51aacc3)

Bug Fixes

  • deps: Update vulnerable dependencies (cae591e)
  • pact-node: Bump pact-node to ^10.7.0, bringing a couple of fixes useful for debugging (25ecd71)

9.8.2 (2020-03-20)

9.8.1 (2020-03-16)

Bug Fixes

  • package.json & package-lock.json to reduce vulnerabilities (#418) (c1c7090)

9.8.0 (2020-03-02)

Features

9.7.0 (2020-02-17)

Features

  • upgrade Pact Node to 10.3.1 (4503b32)

9.6.1 (2020-01-23)

Bug Fixes

  • dependencies: Move bunyan-prettystream to a dependency instead of a dev dependency (805ed11)

9.6.0 (2020-01-01)

Features

  • add email address matcher (14e8974)
  • email: add simplified email address format (f5ea38e)

9.5.0 (2019-11-10)

Features

  • update pact-node to ^10.2.1 (100914f)

9.4.0 (2019-11-08)

Features

  • update pact-node to ^10.2.0 (c96cc89)

9.3.0 (2019-11-08)

Features

  • update pact-node to ^10.2.0 (f64cf69)

9.2.4 (2019-11-08)

Bug Fixes

  • deps: Update vulnerable dependencies (f5d798a)

9.2.3 (2019-11-08)

Bug Fixes

  • deps: Upgrade vulnerable dependencies and correct peer dependencies (#388) (4a19161)
  • examples: Set jasmine timeout in Jest example, preventing brittle tests (fixes #383) (#386) (5f76433)
  • net: stop port check from failing due to ipv6 unavailability (#381) (#389) (9ae53c2)

9.2.2 (2019-10-28)

Bug Fixes

  • deps: Update pact-node to ^10.0.1 (844870d)

9.2.1 (2019-10-17)

9.2.0 (2019-10-08)

Bug Fixes

  • examples: correct karma/jasmine example to use jasmine instead of mocha (#365) (96a0758)
  • MessageProvider: Shut down test environment even if message provider throws an error (#366) (3d66117)
  • upgrade vulnerable dependencies (2380b75)

Features

  • Automatically set changeOrigin: true for non-local verifications (#319) (60f2dc3), closes #280 #281 #282
  • grahpql: allow operation to have null (88acdc0)

9.1.1 (2019-09-05)

Bug Fixes

  • Upgrade pact-node minimum version to bring in broker auth with token (41844fe)

9.1.0 (2019-08-07)

Bug Fixes

  • tests: correct test that would not compile (8cafbbf)
  • types: correct consumerVersionTag in verifier type (fixes #341) (7f6a87d)

Features

9.0.1 (2019-07-17)

Bug Fixes

  • add pactBrokerToken to match pact-node VerifierOptions (89df786)

9.0.0 (2019-07-16)

Bug Fixes

deps

  • pact-node: bump version of pact-node to 9.0.0 (cede852)

BREAKING CHANGES

  • pact-node: pact-node 9.0.0 removes the pact-cli wrapper in favour of exposing the pact-standalone binaries as binstubs. Scripts using the pact cli will need to be updated to use the standalone binaries.

8.2.6 (2019-06-18)

8.2.5 (2019-06-18)

8.2.4 (2019-05-15)

8.2.3 (2019-05-15)

8.2.2 (2019-04-26)

8.2.1 (2019-04-26)

Bug Fixes

  • verifier: providerStateSetupUrl passed to Verifier constructor should take precedence (#295) (9d118a8)

8.2.0 (2019-04-12)

Features

  • graphql: export graphql apis for pact web. Fixes #283 (36ea8d1)

8.1.2 (2019-04-12)

Bug Fixes

  • example: ensure 401 case has invalid bearer token (0dd519b)

8.1.1 (2019-04-11)

8.1.0 (2019-03-29)

Features

8.0.5 (2019-03-12)

Bug Fixes

  • verifier: add changeOrigin flag for http-proxy (4536be5), closes #282

8.0.4 (2019-03-11)

Bug Fixes

  • messages: prevent message proxy from running twice (50219b1)
  • veriry: allow self-signed certificates in provider verification. Fixes #280 (122eb24)

8.0.3 (2019-03-11)

Bug Fixes

  • messages: prevent message proxy from running twice (50219b1)
  • veriry: allow self-signed certificates in provider verification. Fixes #280 (122eb24)

8.0.2 (2019-02-23)

8.0.1 (2019-02-23)

8.0.0 (2019-02-23)

Bug Fixes

  • npm: npm lock got out of sync (a9bed4f)
  • rename error classes to lowercase (16b7686)

Features

  • dynamic-proxy: working dynamic proxy code with tests (d8e2eec)
  • proxy: add docs and e2e examples of filters and stateHandlers (5561980)
  • proxy: cleanup verifier interface (63a661b)

7.4.0 (2019-02-22)

Bug Fixes

Features

  • pact-web provider.addInteraction to allow Interaction instance [#270] (0814d68)

7.3.0 (2019-02-09)

Bug Fixes

  • port-check: make port check more resilient. Fixes #49 (ee0aa71)

Features

  • configuration: return configuration from setup() (11af9e4), closes #259

7.2.0 (2018-11-28)

Bug Fixes

Features

  • examples: add array bracket notation example to jest tests (93c1572)
  • isodate-matcher: ensure minimum 3 precision on iso data matcher (b9144bb)

7.1.0 (2018-11-28)

Features

  • apollo-graphql: add Apollo specific GraphQL interface. Fixes #254 (cab8328)

7.0.4 (2018-11-24)

Bug Fixes

  • graphql: omit variables and operation name if empty. Fixes #243 (0ac2709)
  • vulnerabilities: upgrade version of pact-node (#244) (d8214e6)

7.0.3 (2018-11-07)

Bug Fixes

  • apply logLevel to local logger (6e31407)

7.0.2 (2018-10-27)

Bug Fixes

  • graphql: allow arbitrary operation names in GraphQL interface #235 (16df628)
  • interaction-failure: clear interactions on any verify() (fbc5ac0), closes #231
  • matchers: allow integers/decimals to be 0 (#236) (c40ce32)

7.0.1 (2018-10-15)

Bug Fixes

  • api: repair incorrect absolute import to 'pact'. Fixes #229 (aa22fae)

7.0.0 (2018-10-09)

Bug Fixes

  • README.md: providerVersion is a string not a boolean (#217) (15706cc)
  • test: fix port unavailable test on windows (c41a934)

Chores

  • deprecate: deprecate Node version < 6 (c778880)

BREAKING CHANGES

  • deprecate: No longer supporting Node versions 4 or 5.

6.0.2 (2018-10-01)

Bug Fixes

  • examples/typescript: fix example failing to run (f2ed7d7)
  • examples/typescript: fix the typings for getMeDogs (42bbb9a)
  • examples/typescript: missing dependencies (314119d)
  • vulnerabilities: run npm audit fix on e2e tests (934789f)

6.0.1 (2018-08-19)

Bug Fixes

  • test: add mocha.opts for mocha tests (765f272)
  • test: remove async usage in examples (11368c8)

5.9.1 (2018-05-10)

Bug Fixes

  • interaction: include response body if set to empty string (2db0f23)

6.0.0-alpha.15 (2018-07-17)

Bug Fixes

  • interaction: include response body if set to empty string (abc20d4)

6.0.0-alpha.14 (2018-05-08)

Features

  • message: modify message: content -> contents (38e57a8)
  • upgrade: update to pact-node 6.16.x (c1d938b)

6.0.0-alpha.13 (2018-04-29)

Features

  • graphql: escape queries with variables (8b64dd4)

6.0.0-alpha.12 (2018-04-22)

Features

  • example: example GraphQL pact test (3280a81)
  • graphql: add basic GraphQL wrapper function (641e0e7)
  • message: tidy up Message interface and tests (58c334c)

6.0.0-alpha.11 (2018-04-22)

Features

  • example: example GraphQL pact test (3280a81)
  • graphql: add basic GraphQL wrapper function (641e0e7)
  • message: tidy up Message interface and tests (58c334c)

6.0.0-alpha.10 (2018-04-20)

Bug Fixes

  • Replace packpath with pkginfo to get metadata in more reliable f… (#175) (5abb32e)

6.0.0-alpha.9 (2018-04-20)

Bug Fixes

  • resolve package.json for version metadata regardless of nesting (#174) (9b771c6)

6.0.0-alpha.8 (2018-04-15)

Features

  • messages: setup provider states in verification (57f7352)

6.0.0-alpha.7 (2018-04-05)

6.0.0-alpha.6 (2018-04-05)

6.0.0-alpha.5 (2018-04-04)

Features

  • messages: implement v3 compatible provider states (8e113a5)

6.0.0-alpha.4 (2018-04-01)

Bug Fixes

  • test: fix promise resolution in test (ce31f31)

Features

  • example: working serverless example with pact. #166 (d4a49f5)
  • message: fix message structure sent to consumer verify(). #166 (ee1ddf0)
  • serverless-example: add basic serverless SNS example (08cd73b)

6.0.0-alpha.2 (2018-03-31)

6.0.0-alpha.1 (2018-03-31)

6.0.0-alpha.0 (2018-03-31)

Features

  • messages: initial WIP for message pacts (fd3526e)

5.9.0 (2018-03-27)

Features

  • upgrade: update to pact-node 6.13.x (b19f069)

5.8.0 (2018-03-25)

Features

  • upgrade: update to pact-node 6.12.x (6e5c2e1)

5.7.0 (2018-02-28)

Features

  • upgrade: update to pact-node 6.11.x. Fixes #63 (f0063c9)

5.6.1 (2018-02-25)

5.6.0 (2018-02-22)

Features

  • upgrade: update to pact-node 6.10.x. Fixes #150 (99ab454)

5.5.1 (2018-02-20)

5.5.0 (2018-02-09)

Features

  • upgrade: update to pact-node 6.8.x (fd4ae99)

5.4.0 (2018-02-08)

Features

  • types: allow builder usage in Pact tests (cb6305b)

5.3.2 (2018-01-11)

5.3.1 (2018-01-06)

Bug Fixes

  • logging: set pact-node log level before constructing server #139 (b2f5c2d)
  • verifier: properly wrap pact-node q promise in verifier (affca89)

5.3.0 (2017-12-11)

Features

  • parallel: allow pactfileWriteMode to support 'merge'. #124 (81e1078)

5.2.0 (2017-12-10)

Bug Fixes

  • jest: update jest example to be compatible with v21.x.x (#132) (7fabfc4)

Features

  • examples: extending ava examples with matchers (51fb8ae)
  • mock-service: pass arguments to CLI not API (2b9053c), closes #105
  • pact-node: update to latest pact-node 6.4.x (2430ee0), closes #131

5.1.0 (2017-12-08)

Bug Fixes

  • jest: update jest example to be compatible with v21.x.x (#132) (7fabfc4)

Features

  • examples: extending ava examples with matchers (51fb8ae)
  • pact-node: update to latest pact-node 6.4.x (3d8aef0)

5.0.3 (2017-12-06)

5.0.0 (2017-12-06)

Bug Fixes

  • amd: do not name AMD module in UMD #98 (fced1ab)
  • build: fix for bash script and output helpful information during projects tests (192f9e4)
  • examples: update jasmine karma example with best practice #122 (93cba30)
  • examples: update mocha karma example with best practice #122 (a62d00f)
  • src: fix typo in eachLike error message (601d158)
  • tests: update e2e tests with latest API (09a9f03)
  • verification: pass validation error message on #114 (302357f)

Features

  • api: cleanup public API (39dfc45)
  • finalise: warn if finalise called more than once (bc52810)
  • karma: relax consumer/provider requirement in MockService #96 (62a9c44)
  • matching: add a number of common matchers to DSL (4259171)
  • pact-node: upgrade to latest pact-node 5.1.x (fde380e)
  • pact-node: upgrade to pact-node 5.2.1 (f9bd4ae)
  • pact-server: allow running mock server on non-local host #115 (b6866ef)
  • pact-web: refactor PactWeb module (95b26c4)
  • release: update release process to use standard-version (ae96806)
  • types: reexport Interaction and MockService namespace #117 (e1b658f)
  • types: reexport Interaction and MockService namespace into pact-web #117 (c3cd435)
  • typescript: add integration pact tests (3b2279a)
  • typescript: fix pact-web and karma tests (91ef75c)
  • typescript: initial TypeScript setup (c6e6c3a)

BREAKING CHANGES

  • api: - Provider verification exposed via a Verifier class
  • Matchers exposed through separate sub-module
  • pact-web: Requires constructor to create now.

4.2.1 (2017-11-05)

4.2.0 (2017-11-05)

Features

  • types: add TS bindings for pact-web standalone. Fixes #92 (d436862)

4.1.0 (2017-10-18)

Features

  • release: update release process to use standard-version (47d118d)

4.0.0 (2017-10-18)

Bug Fixes

  • src: fix typo in error message (e91588c)
  • verification: pass validation error message on (3041282)

Features

  • pact-node: upgrade to pact-node 5.x.x (6d2ad81)
  • pact-server: Allow to run pact mock server on a host other than localhost/127.0.0.1 (e24be20)

3.0.1 (2017-09-19)

Bug Fixes

  • lint: fix lint in mock service (e4c61b1)
  • tests: update e2e tests with timeout for CI builds (f141c5e)
  • typo: cosmetic cleanup for typo of wrong project name (18d49f6)

Features

  • karma: relax consumer/provider requirement in MockService (e9f3a4a)

2.7.0 (2017-08-06)

Bug Fixes

  • gitignore: ignore IDE generated project files (84b78c3)
  • issue_template: Corrected typos (bac51ad)

Features

  • example: adding example for the AVA test framework (65e8314)
  • upgrade: upgrade to latest pact node v4.12.0 (50e1041)

2.6.0 (2017-06-13)

2.5.0 (2017-05-15)

2.4.1 (2017-05-12)

Features

  • writemode: update pactFileWriteMode flag and docs (6b32990)

2.4.0 (2017-05-11)

Bug Fixes

  • providerstate: make providerState serialisation spec compliant #12 (cc44554)

Features

  • mock service: add pactfile_write_mode option handling (da92274)
  • verifications: update example to publish verification results (592b9db)

2.3.4 (2017-04-26)

Features

  • pact-web: only deploy pact-web on tagged master (a66cbea)

2.3.3 (2017-04-21)

Features

  • port-check: check if port is available during setup() #37 (c729d8e)
  • typescript: add TypeScript annotations (8eeb561)

2.3.1 (2017-04-03)

2.2.1 (2017-03-12)

Bug Fixes

  • test: fix logic issue in karma tests that was passing for the wrong reasons (080898f)
  • test: update karma jasmine test to properly fail tests if verification fails. (802d5dc)
  • test: update karma mocha test to fail if verification fails (98a6380)

2.2.0 (2017-02-27)

Features

  • ssl: add ability to specify custom ssl key + cert #29 (c54d224)

2.1.0 (2017-02-27)

Features

  • test: update end-to-end test example (cb38b17)
  • verify: update to latest pact-node including ability to set verification timeout #28 (4d0901e)

2.0.1 (2017-02-26)

Bug Fixes

  • pact-node and cli-color should be dependencies (#26 #25) (83c8af3)

2.0.0 (2017-02-22)

Bug Fixes

  • api: remove redundant responseParser and tests (a06a14d)
  • test: properly pass through ssl flag (bc3120d)
  • test: set timeout to 10s for Travis builds (e76d0e8)
  • test: update all mainline tests to match new API (936a75d)
  • test: update e2e test to properly wait for pact finalisation (b98c1f9)
  • test: update formatting in integration test (6bd19c9)
  • test: update jest tests with new API, fixes #21 (4eb2e1c)
  • test: update mocha tests with new API, fixes #22 (2062d6d)
  • tests: remove trailing semi-colons for consistency (7a9565d)

Features

  • api: redesign API to make it simpler to interact with (67482d1)
  • examples: update e2e provider test to use mocha interface (898203a)
  • karma: update code formatting (ef27b7c)
  • karma: update tests for karma suite and adapted Pact API for Karma (7182c7b)

1.0.0 (2017-01-21)

Features

  • example: add better readme, cleanup linting for E2E example (4a8e8cb)
  • examples: running consumer tests for E2E example (274f18f)
  • examples: update docu for e2e example (491f641)
  • examples: WIP e2e example (14a464c)
  • examples: working e2e example (24b9888)

1.0.0-rc.5 (2016-08-28)

Bug Fixes

  • readme: fix example in readme (f0eeb0f)
  • style: remove empty space breaking linter (62a72d8)

Features

  • interceptor: remove Interceptor from DSL (0b9e4f4)

1.0.0-rc.4 (2016-08-02)

Features

  • app: update distribution files (8f9f7e2)

1.0.0-rc.3 (2016-08-01)

1.0.0-rc.2 (2016-07-11)

Bug Fixes

  • lib: better handling HTTP responses (7b07821)