Skip to main content

Tooling integration - MSW

note

Official PactFlow adapter

Create MSW (mock-service-worker) mocks and generate pact contracts from recorded interactions.

With @pactflow/pact-msw-adapter - npm

Did you know?

One of the quickest ways to see this in action in a full CI/CD flow, is to pick the MSW consumer, in our mix & match Bi-Directional Quick-Start Guide

Install

  1. Install MSW
  2. Install @pactflow/pact-msw-adapter

The following will install both msw and @pactflow/pact-msw-adapter

npm install --save-dev msw @pactflow/pact-msw-adapter

Define Mocks

Define your MSW Mocks

MSW Quick Start Reference - Rest-API

examples/react/src/mocks/mockData.js
loading...
examples/react/src/mocks/handlers.js
loading...

Integrate MSW

MSW Quick Start Reference - Integrate MSW with your code

MSW Quick Start Reference - Browser

examples/react/src/mocks/browser.js
loading...
examples/react/src/index.js
loading...

Setup pact-msw-adapter

We need to setup pact-msw-adapter in our test framework setup hooks.

Please read the reference guide, for up-to-date information on setupPactMswAdapter configuration options:

pact-msw-adapter Reference

The adapter uses by default node’s filesystem to write pact files to disk. This makes it incompatible with browser environments where fs is not available. To overcome this, pact-msw-adapter allows for defining custom functions for writing files to disk.

This example uses Cypress's cy.writeFile method

examples/react/cypress/integration/pactFromMswWorker.spec.js
loading...

Write your tests

No additional magic is needed. You can just start writing your tests.

This example uses Cypress

examples/react/cypress/integration/pactFromMswWorker.spec.js
loading...

Run your tests in the usual manner for your framework.

Well done!

You should now see a Pact file generated in your specified folder; the default is ./msw-generated-pacts - These are now ready for upload to the PactFlow Platform.