npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@ijuani/msw-pact

v0.5.0-a6

Published

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

Downloads

4

Readme

msw-pact

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

Note:- This is an alpha version and interface changes are to be expected. If you wish to contribute please get in touch!

How to use

In your tests, import msw and msw pact.

import { setupServer } from "msw/node";
import { setupMswPact } from "./mswPact";

Instantiate your msw server and setup msw-pact

const server = setupServer();
const mswPact = setupMswPact({
  server,
  options: { consumerName: "myTestConsumer" },
});

The following parameters are accepted

| Parameter | Required? | Type | Description | | --------- | --------- | -------------- | ---------------------------------------------------------- | | server | true | SetupServerApi | server provided by msw | | options | false | MswPactOptions | Override msw-pact options - see below for available params |

In your test framework, setup mock-service-work and msw-pact similar to your pre/post test setup. Jest shown.

beforeAll(async () => {
  server.listen();
});
beforeEach(async () => {
  mswPact.listen();
});
afterEach(async () => {
  server.resetHandlers();
  const pactsGeneratedAfterTest = await mswPact.returnPacts();
  console.log(pactsGeneratedAfterTest);
});
afterAll(async () => {
  const allPactsGeneratedAfterTestSuite = await mswPact.returnAllPacts();
  console.log(allPactsGeneratedAfterTestSuite.length); // returns 2
  console.log(JSON.stringify(allPactsGeneratedAfterTestSuite)); // returns any array of generated pacts
  mswPact.clear();
  console.log(allPactsGeneratedAfterTestSuite); // returns []
  server.close();
});

options

| Parameter | Required? | Type | Default | Description | | -------------- | --------- | ------- | ----------------------- | -------------------------------------------------------- | | timeout | false | number | 200 | amount of time in ms, returnPact() will wait for a match | | pactOutDir | false | string | ./msw_generated_pacts | write pacts to the specified location | | debug | false | boolean | false | Print verbose logging | | consumerName | false | string | consumer | The consumer name | | providerName | false | string | provider | The provider name |

An example

Taken from ./src/pactFromMsw.msw.spec.ts

Testing an API client, used in a react application

import API from "../examples/react/src/api";
import { rest } from "msw";
import { setupServer } from "msw/node";
import { setupMswPact } from "./mswPact";

const server = setupServer();
const mswPact = setupMswPact({ server });

describe("API - With MSW mock generating a pact", () => {
  beforeAll(async () => {
    server.listen();
  });
  beforeEach(async () => {
    mswPact.listen();
  });
  afterEach(async () => {
    server.resetHandlers();
    const pactsGeneratedAfterTest = await mswPact.returnPacts();
    console.log(pactsGeneratedAfterTest);
  });
  afterAll(async () => {
    mswPact.writePacts(); // writes the pacts to a file
    const allPactsGeneratedAfterTestSuite = await mswPact.returnAllPacts();
    console.log(allPactsGeneratedAfterTestSuite.length); // returns 2
    console.log(JSON.stringify(allPactsGeneratedAfterTestSuite)); // returns any array of generated pacts
    mswPact.clear();
    console.log(allPactsGeneratedAfterTestSuite); // returns []
    server.close();
  });

  test("get all products", async () => {
    const products = [
      {
        id: "09",
        type: "CREDIT_CARD",
        name: "Gem Visa",
      },
    ];
    server.use(
      rest.get(API.url + "/products", (req, res, ctx) => {
        return res(ctx.status(200), ctx.json(products));
      })
    );

    const respProducts = await API.getAllProducts();
    expect(respProducts).toEqual(products);
  });

  test("get product ID 10", async () => {
    const product = {
      id: "10",
      type: "CREDIT_CARD",
      name: "28 Degrees",
    };
    server.use(
      rest.get(API.url + "/product/10", (req, res, ctx) => {
        return res(ctx.status(200), ctx.json(product));
      })
    );

    const respProduct = await API.getProduct("10");
    expect(respProduct).toEqual(product);
  });

  test("unhandled route", async () => {
    await expect(API.getProduct("10")).rejects.toThrow(
      "connect ECONNREFUSED 127.0.0.1:8081"
    );
  });
});

This test will generate the following two pacts

{
  "consumer": { "name": "consumer" },
  "provider": { "name": "provider" },
  "interactions": [
    {
      "description": "412bfbc9-0804-4955-83b3-2ff9c3134a11",
      "providerState": "",
      "request": {
        "method": "GET",
        "path": "/product/10",
        "headers": {
          "accept": "application/json, text/plain, */*",
          "authorization": "Bearer 2021-05-04T17:49:26.713Z",
          "user-agent": "axios/0.19.2",
          "x-msw-request-id": "412bfbc9-0804-4955-83b3-2ff9c3134a11",
          "cookie": ""
        }
      },
      "response": {
        "status": 200,
        "headers": {
          "x-powered-by": "msw",
          "content-type": "application/json"
        },
        "body": { "id": "10", "type": "CREDIT_CARD", "name": "28 Degrees" }
      }
    }
  ],
  "metadata": { "pactSpecification": { "version": "2.0.0" } }
}
{
  "consumer": { "name": "consumer" },
  "provider": { "name": "provider" },
  "interactions": [
    {
      "description": "ffdfc4c4-0082-4e5c-8490-3c3a62f7d13b",
      "providerState": "",
      "request": {
        "method": "GET",
        "path": "/products",
        "headers": {
          "accept": "application/json, text/plain, */*",
          "authorization": "Bearer 2021-05-04T17:49:26.690Z",
          "user-agent": "axios/0.19.2",
          "x-msw-request-id": "ffdfc4c4-0082-4e5c-8490-3c3a62f7d13b",
          "cookie": ""
        }
      },
      "response": {
        "status": 200,
        "headers": {
          "x-powered-by": "msw",
          "content-type": "application/json"
        },
        "body": [{ "id": "09", "type": "CREDIT_CARD", "name": "Gem Visa" }]
      }
    }
  ],
  "metadata": { "pactSpecification": { "version": "2.0.0" } }
}

Generating msw mocks from pact files.

If you have an existing pact file, you can generate msw mocks from these.

Taken from ./src/mswFromPact.msw.spec.ts

Testing an API client, used in a react application

import API from "../examples/react/src/api";
import { setupPactMsw } from "mswPact";
import pactData from "./pact/frontendwebsite-productservice.json";

const pactMsw = setupPactMsw();
pactMsw.setupMswPactHandlers(pactData);
const pactMswServer = pactMsw.pactMswServer;

describe("API - With MSW mock generated from pact", () => {
  beforeAll(() => pactMswServer.listen());
  afterEach(() => pactMswServer.resetHandlers());
  afterAll(() => pactMswServer.close());
  test("get all products", async () => {
    const products = [
      {
        id: "09",
        type: "CREDIT_CARD",
        name: "Gem Visa",
      },
    ];
    const respProducts = await API.getAllProducts();
    expect(respProducts).toEqual(products);
  });

  test("get product ID 10", async () => {
    const product = {
      id: "10",
      type: "CREDIT_CARD",
      name: "28 Degrees",
    };
    const respProduct = await API.getProduct("10");
    expect(respProduct).toEqual(product);
  });
});