Skip to main content

Tooling integration - MSW

note

Official Pactflow adapter

Create MSW (mock-service-worker) mocks, and generate pact contracts from the 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, to up-to-date information on all the configuration options for setupPactMswAdapter

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 is using 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 is using 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.