10.18.0 • Published 1 month ago

@pact-foundation/pact-node v10.18.0

Weekly downloads
133,677
License
MIT
Repository
github
Last release
1 month ago

[Build and test Known Vulnerabilities npm license dependencies slack

Pact Node

An idiomatic Node wrapper for the Pact CLI Tools.

NOTE: If you are new to Pact and are wanting to get started with contract testing, you almost certainly don't want to use this package. Head over to Pact JS instead.

Installation

npm install @pact-foundation/pact-node --save

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. To respect your privacy, anyone can turn it off by simply adding a 'do not track' flag within their package.json file:

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

Pact Download Location

For those that are behind a corporate firewall or are seeing issues where our package downloads binaries during installation, you can download the binaries directly from our github releases, and specify the location where you want Pact to get the binaries from using the 'config' section in your package.json file:

{
	"name": "some-project",
	...
	"config": {
		"pact_binary_location": "/home/some-user/Downloads"
	},
	...
}

It will accept both a local path or an http(s) url. It must point to the directory containing the binary needed as the binary name is appended to the end of the location. For the example given above, Pact will look for the binary at /home/some-user/Downloads/pact-1.44.0-win32.zip for a Windows system. However, by using this method, you must use the correct Pact version binary associated with this version of Pact-Node. For extra security measurements, checksum validation has been added to prevent tampering with the binaries.

If your environment uses self-signed certificates from an internal Certificate Authority (CA), you can configure this using the standard options in an npmrc file as per below:

~/.npmrc:

cafile=/etc/ssl/certs/ca-certificates.crt
strict-ssl=true

Skip Pact binary downloading

You can also force Pact to skip the installation of the binary during npm install by setting PACT_SKIP_BINARY_INSTALL=true. This feature is useful if you want to speed up builds that don't need Pact and don't want to modify your projects dependencies.

Note that pact-node will not be functional without the binary.

PACT_SKIP_BINARY_INSTALL=true npm install

Which Library/Package should I use?

TL;DR - you almost always want Pact JS.

PurposeLibraryComments
Synchronous / HTTP APIsPact JS
Asynchronous APIsPact JS
Node.jsPact JS
Browser testingPact WebYou probably still want Pact JS. See Using Pact in non-Node environments *
Isomorphic testingPact WebYou probably still want Pact JS. See Using Pact in non-Node environments *
Publishing to Pact BrokerPact NodeIncluded in Pact JS distribution

* 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.

Usage

Simply require the library and call the create function to start the mock service

var pact = require("@pact-foundation/pact-node");
var server = pact.createServer({ port: 9999 });
server.start().then(function() {
	// Do your testing/development here
});

Or if you're using Typescript instead of plain old Javascript

import pact from "@pact-foundation/pact-node";
const server = pact.createServer({ port: 9999 });
server.start().then(() => {
	// Do your testing/development here
});

Or you can also use the CLI

$# pact mock --port 9999

To see the list commands possible with the CLI, simply ask for help $# pact --help

Documentation

Set Log Level

var pact = require("@pact-foundation/pact-node");
pact.logLevel("debug");

Mock Servers

Mock servers are used by Pact to record interactions and create pact contracts.

Create Mock Server

var pact = require('@pact-foundation/pact-node');
var server = pact.createServer({
	...
});

Options:

ParameterRequired?TypeDescription
portfalsenumberPort number that the server runs on, defaults to random available port
hostfalsestringHost on which to bind the server on, defaults to 'localhost'. Supports '0.0.0.0' to bind on all IPv4 addresses on the local machine.
logfalsestringFile to log output on relative to current working directory, defaults to none
logLevelfalseLogLevel (string)Log level to pass to the pact core. One of "DEBUG", "ERROR", "WARN", "INFO"
sslfalsebooleanCreate a self-signed SSL cert to run the server over HTTPS , defaults to false
sslcertfalsestringPath to a custom self-signed SSL cert file, 'ssl' option must be set to true to use this option, defaults to none
sslkeyfalsestringPath a custom key and self-signed SSL cert key file, 'ssl' option must be set to true to use this, defaults to none
corsfalsebooleanAllow CORS OPTION requests to be accepted, defaults to 'false'
dirfalsestringDirectory to write the pact contracts relative to the current working directory, defaults to none
specfalsenumberThe pact specification version to use when writing pact contracts, defaults to '1'
consumerfalsestringThe name of the consumer to be written to the pact contracts, defaults to none
providerfalsestringThe name of the provider to be written to the pact contracts, defaults to none
pactFileWriteModefalseoverwrite OR update OR mergeControl how the pact file is created. Defaults to "overwrite"
formatfalsejson OR xmlFormat to write the results as, either in JSON or XML, defaults to JSON
outfalsestringWrite output to a file instead of returning it in the promise, defaults to none

List Mock Servers

If you ever need to see which servers are currently created.

var pact = require("@pact-foundation/pact-node");
var servers = pact.listServers();
console.log(JSON.stringify(servers));

Remove All Mock Servers

Remove all servers once you're done with them in one fell swoop.

var pact = require("@pact-foundation/pact-node");
pact.removeAllServers();

Start a Mock Server

Start the current server.

var pact = require("@pact-foundation/pact-node");
pact.createServer()
	.start()
	.then(function() {
		// Do something after it started
	});

Stop a Mock server

Stop the current server.

var pact = require("@pact-foundation/pact-node");
pact.createServer()
	.stop()
	.then(function() {
		// Do something after it stopped
	});

Delete a Mock server

Stop the current server and deletes it from the list.

var pact = require("@pact-foundation/pact-node");
pact.createServer()
	.delete()
	.then(function() {
		// Do something after it was killed
	});

Check if a Mock server is running

var pact = require("@pact-foundation/pact-node");
pact.createServer().running;

Mock Server Events

There's 3 different events available, 'start', 'stop' and 'delete'. They can be listened to the same way as an EventEmitter.

var pact = require("@pact-foundation/pact-node");
var server = pact.createServer();
server.on("start", function() {
	console.log("started");
});
server.on("stop", function() {
	console.log("stopped");
});
server.on("delete", function() {
	console.log("deleted");
});

Provider Verification

Read more about Verify Pacts.

var pact = require('@pact-foundation/pact-node');

pact.verifyPacts({
	...
});

Options:

ParameterRequired?TypeDescription
providerBaseUrltruestringRunning API provider host endpoint.
pactBrokerUrlfalsestringBase URL of the Pact Broker from which to retrieve the pacts. Required if pactUrls not given.
providerfalsestringName of the provider if fetching from a Broker
consumerVersionSelectorsfalseConsumerVersionSelector|arrayUse Selectors to is a way we specify which pacticipants and versions we want to use when configuring verifications.
consumerVersionTagsfalsestring|arrayRetrieve the latest pacts with given tag(s)
providerVersionTagsfalsestring|arrayTag(s) to apply to the provider application
includeWipPactsSincefalsestringIncludes pact marked as WIP since this date. String in the format %Y-%m-%d or %Y-%m-%dT%H:%M:%S.000%:z
pactUrlsfalsearrayArray of local pact file paths or HTTP-based URLs. Required if not using a Pact Broker.
providerStatesSetupUrlfalsestringURL to send PUT requests to setup a given provider state
pactBrokerUsernamefalsestringUsername for Pact Broker basic authentication
pactBrokerPasswordfalsestringPassword for Pact Broker basic authentication
pactBrokerTokenfalsestringBearer token for Pact Broker authentication
publishVerificationResultfalsebooleanPublish verification result to Broker (NOTE: you should only enable this during CI builds)
customProviderHeadersfalsearrayHeader(s) to add to provider state set up and pact verificationrequests. eg 'Authorization: Basic cGFjdDpwYWN0'.
providerVersionfalsestringProvider version, required to publish verification result to Broker. Optional otherwise.
enablePendingfalsebooleanEnable the pending pacts feature.
timeoutfalsenumberThe duration in ms we should wait to confirm verification process was successful. Defaults to 30000.
formatfalsestringWhat format the verification results are printed in. Options are json, xml, progress and RspecJunitFormatter (which is a synonym for xml)
verbosefalsebooleanEnables verbose output for underlying pact binary.
logDirfalsestringDirectory to output the pact.log file to
logLevelfalseLogLevel (string)Log level. One of "DEBUG", "ERROR", "WARN", "INFO"

Pact Broker Publishing

var pact = require('@pact-foundation/pact-node');
var opts = {
	...
};

pact.publishPacts(opts).then(function () {
	// do something
});

Options:

ParameterRequired?TypeDescription
pactFilesOrDirstruearrayArray of local Pact files or directories containing them. Required.
pactBrokertruestringURL of the Pact Broker to publish pacts to. Required.
consumerVersiontruestringA string containing a semver-style version e.g. 1.0.0. Required.
pactBrokerUsernamefalsestringUsername for Pact Broker basic authentication. Optional
pactBrokerPasswordfalsestringPassword for Pact Broker basic authentication. Optional
pactBrokerTokenfalsestringBearer token for Pact Broker authentication. Optional
tagsfalsearrayAn array of Strings to tag the Pacts being published. Optional
buildUrlfalsestringThe build URL that created the pact. Optional
branchfalsestringThe branch of the version for which you want to check the verification results. Optional
verbosefalsebooleanEnables verbose output for underlying pact binary.

Pact Broker Deployment Check

var pact = require('@pact-foundation/pact-node');
var opts = {
	...
};

pact.canDeploy(opts)
	.then(function (result) {
		// You can deploy this
    // If output is not specified or is json, result describes the result of the check.
    // If outout is 'table', it is the human readable string returned by the check
	})
	.catch(function(error) {
		// You can't deploy this
    // if output is not specified, or is json, error will be an object describing
    // the result of the check (if the check failed),
    // if output is 'table', then the error will be a string describing the output from the binary,

    // In both cases, `error` will be an Error object if something went wrong during the check.
	});

Options:

ParameterRequired?TypeDescription
pacticipantstrue[]objectsAn array of version selectors in the form { name: String, latest?: string | boolean, version?: string }
specify a tag, use the tagname with latest. Specify one of these per pacticipant
that you want to deploy
pactBrokertruestringURL of the Pact Broker to query about deployment. Required.
pactBrokerUsernamefalsestringUsername for Pact Broker basic authentication. Optional
pactBrokerPasswordfalsestringPassword for Pact Broker basic authentication. Optional
pactBrokerTokenfalsestringBearer token for Pact Broker authentication. Optional
outputfalsejson,tableSpecify output to show, json or table. Optional, Defaults to json.
verbosefalsebooleanEnables verbose output for underlying pact binary.
retryWhileUnknownfalsenumberThe number of times to retry while there is an unknown verification result. Optional
retryIntervalfalsenumberThe time between retries in seconds, use with retryWhileUnknown. Optional
tofalsestringThe tag that you want to deploy to (eg, 'prod')

Stub Servers

Stub servers create runnable APIs from existing pact files.

The interface is comparable to the Mock Server API.

Create Stub Server

var pact = require('@pact-foundation/pact-node');
var server = pact.createStub({
	...
});

Options:

ParameterRequired?TypeDescription
pactUrlstruearrayList of local Pact files to create the stub service from
portfalsenumberPort number that the server runs on, defaults to random available port
hostfalsestringHost on which to bind the server on, defaults to 'localhost'. Supports '0.0.0.0' to bind on all IPv4 addresses on the local machine.
logfalsestringFile to log output on relative to current working directory, defaults to none
logLevelfalseLogLevel (string)Log level to pass to the pact core. One of "DEBUG", "ERROR", "WARN", "INFO"
sslfalsebooleanCreate a self-signed SSL cert to run the server over HTTPS , defaults to 'false'
sslcertfalsestringPath to a custom self-signed SSL cert file, 'ssl' option must be set to true to use this option. Defaults falseto none
sslkeyfalsestringPath a custom key and self-signed SSL cert key file, 'ssl' option must be set to true to use this option false. Defaults to none
corsfalsebooleanAllow CORS OPTION requests to be accepted, defaults to 'false'
timeoutfalsenumberHow long to wait for the stub server to start up (in milliseconds). Defaults to 30000 (30 seconds)

Message Pacts

Create Message Pacts

var pact = require('@pact-foundation/pact-node');
var message = pact.createMessage({
	...
});

Options:

ParameterRequired?TypeDescription
dirtruestringDirectory to write the pact contracts relative to the current working directory, defaults to none
consumertruestringThe name of the consumer to be written to the pact contracts, defaults to none
providertruestringThe name of the provider to be written to the pact contracts, defaults to none
pactFileWriteModefalse"overwrite" | "update" | "merge"Control how the pact file is created. Defaults to "update"
Example
const messageFactory = messageFactory({
	consumer: "consumer",
	provider: "provider",
	dir: dirname(`${__filename}/pacts`),
	content: `{
		"description": "a test mesage",
		"content": {
			"name": "Mary"
		}
	}`
});

messageFactory.createMessage();

CLI Tools

This package also comes with the Pact Standalone Tools available as linked binaries in the standard NPM installation directory (e..g. ./node_modules/.bin).

This means you may call them direct from scripts in your package json, for example:

"scripts": {
  "pactPublish": "pact-broker publish ./pacts --consumer-app-version=$\(git describe\) --broker-base-url=$BROKER_BASE_URL --broker-username=$BROKER_USERNAME --broker-password=BROKER_PASSWORD"`
}
These are available in circumstances where `pact-node` has not yet implemented a feature or access via JavaScript APIs is not desirable. To run the binaries is as simple as the following:

*Example can-i-deploy check*:
```bash
./node_modules/.bin/pact-broker can-i-deploy --pacticipant "Banana Service" --broker-base-url https://test.pact.dius.com.au --latest --broker-username dXfltyFMgNOFZAxr8io9wJ37iUpY42M --broker-password O5AIZWxelWbLvqMd8PkAVycBJh2Psyg1

Computer says no ¯\_(ツ)_/¯

CONSUMER       | C.VERSION | PROVIDER       | P.VERSION | SUCCESS?
---------------|-----------|----------------|-----------|---------
Banana Service | 1.0.0     | Fofana Service | 1.0.0     | false

The verification between the latest version of Banana Service (1.0.0) and version 1.0.0 of Fofana Service failed

The following are the binaries currently made available:

  • pact-mock-service
  • pact-broker
  • pact-stub-service
  • pact-message
  • pact-provider-verifier
  • pact

Windows Issues

Enable Long Paths

Windows has a default path length limit of 260 causing issues with projects that are nested deep inside several directory and with how npm handles node_modules directory structures. To fix this issue, please enable Windows Long Paths in the registry by running regedit.exe, find the key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem\LongPathsEnabled and change the value from 0 to 1, then reboot your computer. Pact should now work as it should, if not, please raise an issue on github.

Contributing

To develop this project, simply install the dependencies with npm install --ignore-scripts, and run npm run watch to for continual development, linting and testing when a source file changes.

Testing

Running npm test will execute the tests that has the *.spec.js pattern.

Questions?

Please search for potential answers or post question on our official Pact StackOverflow.

10.18.0

1 month ago

10.17.7

1 year ago

10.17.5

2 years ago

10.17.6

2 years ago

10.17.4

2 years ago

10.17.3

2 years ago

10.17.2

2 years ago

10.15.0

2 years ago

10.16.0

2 years ago

10.16.1

2 years ago

10.17.0

2 years ago

10.17.1

2 years ago

10.14.0

2 years ago

10.13.10

2 years ago

10.13.9

2 years ago

10.13.8

2 years ago

10.13.7

3 years ago

10.13.6

3 years ago

10.13.4

3 years ago

10.13.5

3 years ago

10.13.3

3 years ago

10.13.2

3 years ago

10.13.1

3 years ago

10.13.0

3 years ago

10.12.2

3 years ago

10.12.1

3 years ago

10.11.11

3 years ago

10.11.9

3 years ago

10.11.10

3 years ago

10.11.8

3 years ago

10.11.7

3 years ago

10.11.6

3 years ago

10.11.5

3 years ago

10.11.4

3 years ago

10.11.3

3 years ago

10.11.2

3 years ago

10.11.1

3 years ago

10.11.0

3 years ago

10.10.2

3 years ago

10.10.1

4 years ago

10.10.0

4 years ago

10.9.7

4 years ago

10.9.6

4 years ago

10.9.5

4 years ago

10.9.4

4 years ago

10.9.3

4 years ago

10.9.2

4 years ago

10.9.1

4 years ago

10.9.0

4 years ago

10.8.1

4 years ago

10.8.0

4 years ago

10.7.0

4 years ago

10.7.1

4 years ago

10.6.0

4 years ago

10.5.0

4 years ago

10.4.0

4 years ago

10.3.1

4 years ago

10.2.4

4 years ago

10.2.3

4 years ago

10.2.2

4 years ago

10.2.1

4 years ago

10.2.0

4 years ago

10.0.2-beta.0

4 years ago

10.0.1

4 years ago

10.0.0

4 years ago

9.0.7

4 years ago

9.0.6

4 years ago

9.0.5

4 years ago

9.0.4

5 years ago

9.0.3

5 years ago

9.0.2

5 years ago

9.0.1

5 years ago

9.0.0

5 years ago

8.6.2

5 years ago

8.6.0

5 years ago

8.5.1

5 years ago

8.5.0

5 years ago

8.4.1

5 years ago

8.4.0

5 years ago

8.3.3

5 years ago

8.3.2

5 years ago

8.3.1

5 years ago

8.3.0

5 years ago

8.2.0

5 years ago

8.1.2

5 years ago

8.1.1

5 years ago

8.1.0

5 years ago

8.0.0

5 years ago

7.0.1

5 years ago

7.0.0

5 years ago

6.21.5

5 years ago

6.21.4

5 years ago

6.21.3

5 years ago

6.21.2

5 years ago

6.21.1

5 years ago

6.21.0

5 years ago

6.20.2

5 years ago

6.20.1

5 years ago

6.20.0

5 years ago

6.19.12

5 years ago

6.19.11

6 years ago

6.19.10

6 years ago

6.19.9

6 years ago

6.19.8

6 years ago

6.19.8-rc

6 years ago

6.19.7

6 years ago

6.19.6

6 years ago

6.19.4

6 years ago

6.19.3

6 years ago

6.19.2

6 years ago

6.19.1

6 years ago

6.19.0

6 years ago

6.18.3

6 years ago

6.18.1

6 years ago

6.18.0

6 years ago

6.17.0

6 years ago

6.16.4

6 years ago

6.16.3

6 years ago

6.16.2

6 years ago

6.16.1

6 years ago

6.14.4

6 years ago

6.16.0

6 years ago

6.15.0

6 years ago

6.14.3

6 years ago

6.14.2

6 years ago

6.14.1

6 years ago

6.14.0

6 years ago

6.13.0

6 years ago

6.12.3

6 years ago

6.12.2

6 years ago

6.12.1

6 years ago

6.12.0

6 years ago

6.11.0

6 years ago

6.10.1

6 years ago

6.10.0

6 years ago

6.9.0

6 years ago

6.8.0

6 years ago

6.7.4

6 years ago

6.7.3

6 years ago

6.7.2

6 years ago

6.7.1

6 years ago

6.7.0

6 years ago

6.6.0

6 years ago

6.5.0

6 years ago

6.4.1

6 years ago

6.3.0

6 years ago

6.2.0

6 years ago

6.1.0

6 years ago

6.0.0

6 years ago

5.2.1

6 years ago

5.2.0

6 years ago

5.1.3

6 years ago

5.1.2

6 years ago

5.1.1

6 years ago

5.1.0

6 years ago

5.0.1

6 years ago

5.0.0

7 years ago

4.12.0

7 years ago

4.10.0

7 years ago

4.9.2

7 years ago

4.9.1

7 years ago

4.9.0

7 years ago

4.8.3

7 years ago

4.8.2

7 years ago

4.8.1

7 years ago

4.8.0

7 years ago

4.7.0

7 years ago

4.6.0

7 years ago

4.5.4

7 years ago

4.5.3

8 years ago

4.5.2

8 years ago

4.5.1

8 years ago

4.5.0

8 years ago

4.4.4

8 years ago

4.4.3

8 years ago

4.4.2

8 years ago

4.4.1

8 years ago

4.4.0

8 years ago

4.3.2

8 years ago

4.3.0

8 years ago

4.2.1

8 years ago

4.2.0

8 years ago

4.1.1

8 years ago

4.1.0

8 years ago

4.0.3

8 years ago

4.0.2

8 years ago

4.0.1

8 years ago

4.0.0

8 years ago

3.1.0

8 years ago

3.0.0

8 years ago

2.0.1

8 years ago

2.0.0

8 years ago