• Stars
    star
    1,456
  • Rank 32,304 (Top 0.7 %)
  • Language
    TypeScript
  • License
    Other
  • Created over 8 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

JS version of Pact. Pact is a contract testing framework for HTTP APIs and non-HTTP asynchronous messaging systems.

logo

Pact JS

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

Fast, easy and reliable testing for your APIs and microservices.


Pact JS Demo


Pact is the de-facto API contract testing tool. Replace expensive and brittle end-to-end integration tests with fast, reliable and easy to debug unit tests.

  • ⚡ Lightning fast
  • 🎈 Effortless full-stack integration testing - from the front-end to the back-end
  • 🔌 Supports HTTP/REST and event-driven systems
  • 🛠️ Configurable mock server
  • 😌 Powerful matching rules prevents brittle tests
  • 🤝 Integrates with Pact Broker / PactFlow for powerful CI/CD workflows
  • 🔡 Supports 12+ languages

Why use Pact?

Contract testing with Pact lets you:

  • ⚡ Test locally
  • 🚀 Deploy faster
  • ⬇️ Reduce the lead time for change
  • 💰 Reduce the cost of API integration testing
  • 💥 Prevent breaking changes
  • 🔎 Understand your system usage
  • 📃 Document your APIs for free
  • 🗄 Remove the need for complex data fixtures
  • 🤷‍♂️ Reduce the reliance on complex test environments

Watch our series on the problems with end-to-end integrated tests, and how contract testing can help.

----------

Documentation

This readme offers a basic introduction to the library. The full documentation for Pact JS and the rest of the framework is available at https://docs.pact.io/.

Tutorial (60 minutes)

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

Need Help

Installation

npm i -S @pact-foundation/pact@latest

# 🚀 now write some tests!

Looking for the previous stable 9.x.x release?

Requirements

Node 16+ as of pact-js v12

  1. If using pact-js v11 or lower,
    1. make sure the ignore-scripts option is disabled, pact uses npm scripts to compile native dependencies and won't function without it.
    2. Pact uses native extensions and installs them via the node-gyp package. This requires a build chain for a successful installation. See also issue #899. This is now prebuilt in pact-js v12+

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. You can disable tracking by setting the environment variable PACT_DO_NOT_TRACK=1:

----------

Usage

Consumer package

The main consumer interface are the PactV3 class and MatchersV3 exports of the @pact-foundation/pact package.

Writing a Consumer test

Pact is a consumer-driven contract testing tool, which is a fancy way of saying that the API Consumer writes a test to set out its assumptions and needs of its API Provider(s). By unit testing our API client with Pact, it will produce a contract that we can share to our Provider to confirm these assumptions and prevent breaking changes.

In this example, we are going to be testing our User API client, responsible for communicating with the UserAPI over HTTP. It currently has a single method GetUser(id) that will return a *User.

Pact tests have a few key properties. We'll demonstrate a common example using the 3A Arrange/Act/Assert pattern.

import { PactV3, MatchersV3 } from '@pact-foundation/pact';

// Create a 'pact' between the two applications in the integration we are testing
const provider = new PactV3({
  dir: path.resolve(process.cwd(), 'pacts'),
  consumer: 'MyConsumer',
  provider: 'MyProvider',
});

// API Client that will fetch dogs from the Dog API
// This is the target of our Pact test
public getMeDogs = (from: string): AxiosPromise => {
  return axios.request({
    baseURL: this.url,
    params: { from },
    headers: { Accept: 'application/json' },
    method: 'GET',
    url: '/dogs',
  });
};

const dogExample = { dog: 1 };
const EXPECTED_BODY = MatchersV3.eachLike(dogExample);

describe('GET /dogs', () => {
  it('returns an HTTP 200 and a list of docs', () => {
    // Arrange: Setup our expected interactions
    //
    // We use Pact to mock out the backend API
    provider
      .given('I have a list of dogs')
      .uponReceiving('a request for all dogs with the builder pattern')
      .withRequest({
        method: 'GET',
        path: '/dogs',
        query: { from: 'today' },
        headers: { Accept: 'application/json' },
      })
      .willRespondWith({
        status: 200,
        headers: { 'Content-Type': 'application/json' },
        body: EXPECTED_BODY,
      });

    return provider.executeTest((mockserver) => {
      // Act: test our API client behaves correctly
      //
      // Note we configure the DogService API client dynamically to 
      // point to the mock service Pact created for us, instead of 
      // the real one
      dogService = new DogService(mockserver.url);
      const response = await dogService.getMeDogs('today')

      // Assert: check the result
      expect(response.data[0]).to.deep.eq(dogExample);
    });
  });
});

You can see (and run) the full version of this in ./examples/v3/typescript, as well as other examples in the parent folder.

To run the examples

  1. Clone the repo [email protected]:pact-foundation/pact-js.git

Run a single example

  1. Change into the required example folder cd examples/e2e/v3/typescript
  2. Install all the examples dependencies npm install
  3. Run all the example - npm run test

Run all examples

  1. Change into the examples folder cd examples
  2. Install all the examples dependencies ./installAll.sh
  3. Run all the examples ./runAll.sh

----------

Provider package

The main provider interface is the Verifier class of the @pact-foundation/pact package.

Verifying a Provider

A provider test takes one or more pact files (contracts) as input, and Pact verifies that your provider adheres to the contract. In the simplest case, you can verify a provider as per below using a local pact file, although in practice you would usually use a Pact Broker to manage your contracts and CI/CD workflow.

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

// (1) Start provider locally. Be sure to stub out any external dependencies
server.listen(8081, () => {
  importData();
  console.log('Animal Profile Service listening on http://localhost:8081');
});

// (2) Verify that the provider meets all consumer expectations
describe('Pact Verification', () => {
  it('validates the expectations of Matching Service', () => {
    let token = 'INVALID TOKEN';

    return new Verifier({
      providerBaseUrl: 'http://localhost:8081', // <- location of your running provider
      pactUrls: [ path.resolve(process.cwd(), "./pacts/SomeConsumer-SomeProvider.json") ],
    })
      .verifyProvider()
      .then(() => {
        console.log('Pact Verification Complete!');
      });
  });
});

It's best to run Pact verification tests as part of your unit testing suite, so you can readily access stubbing, IaC and other helpful tools.

----------

Compatibility

Specification Compatibility
Version Stable Spec Compatibility Install
11.x.x Yes 2, 3, 4 See installation
10.x.x Yes 2, 3, 4 See installation
9.x.x Yes 2, 3* 9xx

* v3 support is limited to the subset of functionality required to enable language inter-operable Message support.

Roadmap

The roadmap for Pact and Pact JS is outlined on our main website.

Contributing

See CONTRIBUTING.


More Repositories

1

pact-ruby

Enables consumer driven contract testing, providing a mock service and DSL for the consumer project, and interaction playback and verification for the service provider project.
Ruby
2,160
star
2

pact-jvm

JVM version of Pact. Enables consumer driven contract testing, providing a mock service and DSL for the consumer project, and interaction playback and verification for the service provider project.
Kotlin
1,082
star
3

pact-go

Golang version of Pact. Pact is a contract testing framework for HTTP APIs and non-HTTP asynchronous messaging systems.
Go
857
star
4

pact-net

.NET version of Pact. Enables consumer driven contract testing, providing a mock service and DSL for the consumer project, and interaction playback and verification for the service provider project.
C#
845
star
5

pact_broker

Enables your consumer driven contracts workflow
Ruby
702
star
6

pact-python

Python version of Pact. Enables consumer driven contract testing, providing a mock service and DSL for the consumer project, and interaction playback and verification for the service provider project.
Python
501
star
7

pact-specification

Describes the pact format and verification specifications
295
star
8

pact-php

PHP version of Pact. Enables consumer driven contract testing, providing a mock service and DSL for the consumer project, and interaction playback and verification for the service provider project
PHP
244
star
9

pact.io

Pact Foundation Website
HTML
219
star
10

pact-js-core

Core binaries for pact-js, a Contract Testing Framework. NOTE: If you are looking to do Pact contract testing in node, you almost certainly want pact-js, not pact-node.
TypeScript
146
star
11

pact-workshop-js

Pact JS workshop - learn Pact in 60 minutes
JavaScript
129
star
12

pact-workshop-go

Golang Pact workshop
Go
106
star
13

pact-broker-docker

Dockerized Pact Broker
Shell
92
star
14

pact-reference

Reference implementations for the pact specifications
Rust
87
star
15

pact-workshop-jvm-spring

Example Spring Boot project for the Pact workshop
Java
85
star
16

jest-pact

A Pact adaptor for to allow you to easily run tests with Jest
TypeScript
81
star
17

pact-workshop-dotnet-core-v1

A workshop for Pact using .NET Core
C#
76
star
18

pact-stub-server

Standalone pact stub server
Rust
75
star
19

pact-mock_service

Provides a mock service for use with Pact
Ruby
73
star
20

pact_broker-client

A Ruby and CLI client for the Pact Broker. Publish and retrieve pacts and verification results.
Ruby
69
star
21

nestjs-pact

Injectable Pact.js Consumer/Producer for NestJS
TypeScript
48
star
22

devrel

Developer Relations @ Pact - Your map to the Pact landscape for all-comers (maintainers, contributors, users, newbies)
38
star
23

pact-ruby-standalone

A standalone pact command line executable using the ruby pact implementation and Travelling Ruby
Shell
35
star
24

pact-provider-verifier

Cross-platform, generic language, Pact provider verification tool
Ruby
28
star
25

pact-workshop-Maven-Springboot-JUnit5

Pact Maven + Springboot + JUnit5 workshop - learn Pact in 60 minutes
28
star
26

pact-stub-server-archived

Wraps the Pact Rust mock server in a Docker container
Dockerfile
25
star
27

pact-js-mocha

EXPERIMENTAL Mocha Interface for Pact JS (warning: it is not recommended for beginners)
JavaScript
18
star
28

pact-plugins

🏰 Architecture to support Plugins 🔌 with Pact 🔗
Rust
16
star
29

pact-provider-proxy

Allows pact verification against a running provider at a configurable base URL
Ruby
16
star
30

docs.pact.io

Pact documentation website
HTML
15
star
31

pact-broker-chart

This repository houses the Pact Broker Helm Chart
Smarty
11
star
32

karma-pact

Pact Framework Plugin for Karma
Shell
11
star
33

pact-5-minute-getting-started-guide

JavaScript
11
star
34

pact-ruby-cli

Amalgamated Pact Ruby CLI
Shell
11
star
35

pact-support

Shared code for Pact gems
Ruby
7
star
36

pact_broker-serverless

Pact Broker running in AWS Lambda with Serverless
Shell
7
star
37

pact-cplusplus

C++ DSL for Pact Library
HTML
6
star
38

pact-ruby-e2e-example

Code base to use for demonstrating features and recreating issues in the ruby implementation of pact. Please fork it and modify to recreate your own code.
Ruby
5
star
39

pact-xml

XML support for the Pact gem
Ruby
4
star
40

pact-plugin-template-golang

Pact 🔗 Plugin 🔌 template for the GoLang 🐿️ language = 🫶
Go
4
star
41

pact-message-demo

Ruby
4
star
42

pact-consumer-minitest

Minitest support for the Pact Consumer gem
Ruby
4
star
43

serverless-offline-pact

A serverless offline plugin to start one or more pact stub service alongside your serverless application
TypeScript
3
star
44

pact-mock-service-docker

Docker image running the Pact mock service
Ruby
3
star
45

homebrew-pact-ruby-standalone

The Pact Ruby Standalone public homebrew tap for macos/linux homebrew formulae
Shell
3
star
46

.github

The GitHub landing page for Pact - The de-facto contract testing tool
3
star
47

pact-event-bot

TypeScript
2
star
48

pact-standalone-npm

Pact Standalone wrapper for NPM projects
JavaScript
2
star
49

pact-parser

Small server to aid using existing pacts files as data sources in unit and integrational testing.
JavaScript
2
star
50

pact-mock-service-npm

Shell
2
star
51

pact-js-cli

The Broker CLI for Pact, but available to your node scripts
TypeScript
2
star
52

grunt-pact

A grunt task to run pact-node
JavaScript
1
star
53

pactr

R version of Pact. Enables consumer driven contract testing. Please read the Pact.io for specific information about PACT.
R
1
star
54

release-gem

Github action that bumps the version, generates the changelog, releases the gem, and creates a Github release
Shell
1
star
55

mocha-pact

An adaptor to allow you to easily run pact tests with Mocha
TypeScript
1
star
56

pact-ruby-standalone-e2e-example

Code base to use for demonstrating features and recreating issues in the Ruby standalone implementation of pact. Please fork it and modify to recreate your own code.
Shell
1
star
57

cypress-pact

Pact plugin for integrating Pact with Cypress tests
1
star
58

pact-js-dev-config

Shared configs for developers working on pact-js and related projects
JavaScript
1
star
59

blog.pact.io

Ghost application setup for blog.pact.io
SCSS
1
star