Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

pact

Package Overview
Dependencies
Maintainers
2
Versions
30
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

pact

Pact for all things Javascript

  • 1.0.0-rc.5
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
1.5K
decreased by-19.34%
Maintainers
2
Weekly downloads
 
Created
Source

Pact JS

Join the chat at https://gitter.im/realestate-com-au/pact

Build Status Code Climate Coverage Status Issue Count npm

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 on how to get going.

NOTE: we are currently in the process of replacing Pact Consumer JS DSL with this library. Please bare with us whilst we transition. If you want to use Pact with JS and are new to Pact, start here.

Installation

It's easy, simply run the below:

npm install --save-dev pact

Using Pact JS

Consumer Side Testing

The library provides a Verifier Service, Matchers and an API Interceptor:

Verifier Sets up a test double (Verifier Provider API) with expected interactions. It's also responsible for generating Pact files.

Matchers are functions you can use to increase the expressiveness of your tests, and reduce brittle test cases. See the matching docs for more information.

Interceptor is a utility that can be used to intercept requests to the Provider, where it's not simple for you to change your API endpoint.

To use the library on your tests, do as you would normally with any other dependency:

var Pact = require('pact')
var matchers = Pact.Matchers
matchers.term()
matchers.somethingLike()
matchers.eachLike()

Then to write a test that will generate a Pact file, here's an example below - it uses Mocha. There's a bit going on in there as we are spinning up the Pact Verifier Service Provider to mock a real server on the provider server. This is needed because that's where we will record our interactions.

More questions about what's involved in Pact? Read more about it.

Check the examples folder for examples with Karma Jasmine / Mocha. The example below is taken from the integration spec.

var path = require('path')
var chai = require('chai')
var Pact = require('pact')
var request = require ('superagent')
var chaiAsPromised = require('chai-as-promised')
var wrapper = require('@pact-foundation/pact-node')

var expect = chai.expect

chai.use(chaiAsPromised);

describe('Pact', () => {

  // when using the wrapper, you will need to tell it where to store the logs
  // make sure you the folders created before hand
  const mockServer = wrapper.createServer({
    port: 1234,
    log: path.resolve(process.cwd(), 'logs', 'mockserver-integration.log'),
    dir: path.resolve(process.cwd(), 'pacts'),
    spec: 2
  })

  // 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}
    ]
  }]

  var provider

  after(() => {
    wrapper.removeAllServers()
  });

  beforeEach((done) => {
    mockServer.start().then(() => {
      // in order to use the Verifier, simply pass an object like below
      // it should contain the names of the consumer and provider in normal language
      // you can also use a different port if you have multiple providers
      provider = Pact({ consumer: 'My Consumer', provider: 'My Provider', port: 1234 })
      done()
    })
  })

  afterEach((done) => {
    mockServer.delete().then(() => {
      done()
    })
  })

  context('with a single request', () => {
    describe('successfully writes Pact file', () => {

      // add interactions, as many as needed
      beforeEach((done) => {
        provider.addInteraction({
          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
          }
        }).then(() => done())
      })

      // once test is run, write pact and remove interactions
      afterEach((done) => {
        provider.finalize().then(() => done())
      })

      // and this is how the verification process invokes your request
      // and writes the Pact file if all is well, returning you the data of the request
      // so you can do your assertions
      it('successfully verifies', (done) => {
        const verificationPromise = request
          .get('http://localhost:1234/projects')
          .set({ 'Accept': 'application/json' })
          .then(provider.verify)
        expect(verificationPromise).to.eventually.eql(JSON.stringify(EXPECTED_BODY)).notify(done)
      })
    })
  })
})
Provider API Testing

Once you have created Pacts for your Consumer, you need to validate those Pacts against your Provider.

First, install Pact Node:

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

Then run the Provider side verification step:

var pact = require('@pact-foundation/pact-node');
var opts = {
	providerBaseUrl: <String>,       // Running API provider host endpoint. Required.
	pactUrls: <Array>,               // Array of local Pact file paths or Pact Broker URLs (http based). Required.
	providerStatesUrl: <String>,     // URL to fetch the provider states for the given provider API. Optional.
	providerStatesSetupUrl <String>, // URL to send PUT requests to setup a given provider state. Optional.
	pactBrokerUsername: <String>,    // Username for Pact Broker basic authentication. Optional
	pactBrokerPassword: <String>,    // Password for Pact Broker basic authentication. Optional
};

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

That's it! Read more about Verifying Pacts.

Publishing Pacts to a Broker

Sharing is caring - to simplify sharing Pacts between Consumers and Providers, checkout sharing pacts.

var pact = require('@pact-foundation/pact-node');
var opts = {
	pactUrls: <Array>,               // Array of local Pact files or directories containing them. Required.
	pactBroker: <String>,            // URL to fetch the provider states for the given provider API. Optional.
	pactBrokerUsername: <String>,    // Username for Pact Broker basic authentication. Optional
	pactBrokerPassword: <String>     // Password for Pact Broker basic authentication. Optional
};

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

Using Mocha?

Check out Pact JS Mocha.

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

If you would like to implement Pact in another language, please check out the Pact specification and have a chat to one of us on the pact-dev Google group.

The vision is to have a compatible Pact implementation in all the commonly used languages, your help would be greatly appreciated!

Contact

Keywords

FAQs

Package last updated on 28 Aug 2016

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc