Configure Pact JS Consumer Contract tests in Angular

This post describes the steps to configure Karma on an Angular 4+ project to run consumer contract tests using Pact.

1) Install pact and pact-web
yarn add pact –dev
yarn add pact-web –dev

Pact JS is a javascript library to create consumer-driven contract tests.
Pact-web is a module to support Pact in non-Node environments such as Karma.

2) Install Karma Pact
yarn add @pact-foundation/karma-pact –dev

Under the covers karma-pact will be in charge of starting a pact-mock-service in the port localhost:1234 before the tests execution as well as shutting it down when karma finish.

3) Configure Karma to support consumer contract tests
karma.conf.js

frameworks: ['jasmine', '@angular/cli', 'pact'],   // 1) add pact framework
plugins: [
  require('karma-pact'), // 2) add karma-pact plugin
  ...
]
...
pact: [{cors: true, spec: 2, port: 1234, dir: 'pacts/'}],  // 3) configure one or multiple pact-mock-services here
proxies: { // 4) here we can define proxies to redirect requests from our pact tests to the mock server
  '/api/tasks': 'http://localhost:1234/api/tasks'
},

Notice: In some situations, it may be useful to run multiple Pact Mock Servers. For instance, when running tests with karma, if a consumer defines contracts for several providers, the generated Pact contracts may be mixed up. A solution to solve this is to run one Pact Mock Server per provider. Support for multiple services was introduced on karma-pact v1.0.0.

After a successful consumer contract test run, Pact generates contract files and saves them in the /pacts folder.

Run consumer contract tests

At this stage, the project is configured and ready to run contract tests along the rest of unit tests. Tests can be run as usual with
ng test

You can find a working example of this configuration in the next sample app:
https://github.com/paucls/task_list_ui-angular/tree/feature/pact-consumer-contract-tests

In my next article, I explain in more detail how to implement Consumer-Driven Contracts.

Documentation
https://github.com/pact-foundation/pact-js#using-pact-in-non-node-environments
https://github.com/pact-foundation/pact-js/issues/20
https://github.com/pact-foundation/karma-pact
https://github.com/koelec/angular-pact-example
https://github.com/NomiJ/Pact-Angular2-Example

Advertisements

One thought on “Configure Pact JS Consumer Contract tests in Angular

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s