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

msw-inspector

v3.2.0

Published

Inspect requests intercepted by MSW

Downloads

260

Readme

MSW inspector

Build status Npm version Test coverage report

Plug-and-play request assertion utility for any msw mock setup, as highly discouraged by msw authors :)

Why?

From msw docs:

Instead of asserting that a request was made, or had the correct data, test how your application reacted to that request.

There are, however, some special cases where asserting on network requests is the only option. These include, for example, polling, where no other side effect can be asserted upon.

MSW inspector has you covered for these special cases.

How

MSW inspector provides a thin layer of logic over msw life-cycle events.

Each intercepted request is stored as a function mock call retrievable by URL. This allows elegant assertions against request attributes like method, headers, body and query fully integrated with your test assertion library.

Installation

npm install msw-inspector -D

Example

This example uses Jest, but MSW inspector integrates with any testing framework.

import { jest } from '@jest/globals';
import { createMSWInspector } from 'msw-inspector';
import { server } from './your-msw-server';

// Setup MSW inspector (should be declared once as a global test setup routine)
const mswInspector = createMSWInspector({
  mockSetup: server,
  mockFactory: () => jest.fn(), // Provide any function mock supported by your testing library
});

beforeAll(() => {
  mswInspector.setup();
});

beforeEach(() => {
  mswInspector.clear();
});

afterAll(() => {
  mswInspector.teardown();
});

describe('My test', () => {
  it('Performs expected network request', async () => {
    await fetch('http://my.url/path?myQuery=value', {
      method: 'POST',
      headers: {
        myHeader: 'value',
      },
      body: JSON.stringify({
        myBody: 'value',
      }),
    });

    expect(
      await mswInspector.getRequests('http://my.url/path'),
    ).toHaveBeenCalledWith({
      method: 'POST',
      headers: {
        myHeader: 'value',
      },
      body: {
        myBody: 'value',
      },
      query: {
        myQuery: 'value',
      },
    });
  });
});

API

createMSWInspector

Create a MSW inspector instance bound to a specific msw SetupServer or SetupWorker instance:

import { createMSWInspector } from 'msw-inspector';

createMSWInspector({
  mockSetup, // You `msw` SetupServer or SetupWorker instance
  mockFactory, // Function returning a mocked function instance to be inspected in your tests
  requestLogger, // Optional logger function to customize request logs
});

createMSWInspector Options

createMSWInspector accepts the following options object:

 {
  mockSetup: SetupServer | SetupWorker;
  mockFactory: () => FunctionMock;
  requestLogger?: (req: MockedRequest) => Promise<Record<string, unknown>>;
}

| Option | Description | Default value | | ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | | mockSetup (required) | The instance of msw mocks expected to inspect (setupWorker or setupServer result) | - | | mockFactory (required) | A function returning the function mock preferred by your testing framework: It can be () => jest.fn() for Jest, () => sinon.spy() for Sinon, () => vi.fn() for Vitest, etc... | - | | requestLogger | Customize request records with your own object. Async function. | See requestLogger |

getRequests

Returns a promise returning a mocked function pre-called with all the request records whose absolute url match the provided one.

The matching url can be provided as:

  • plain absolute url string
  • path-to-regexp matching pattern
  • regular expression (also matches against query string)
// Full string match
await mswInspector.getRequests('http://my.url/path/foo');

// Url matching pattern
await mswInspector.getRequests('http://my.url/path/:param');

// Full url regular expression match
await mswInspector.getRequests(/.+\?query=.+/);

By default, each matching request results into a mocked function call with the following request log record:

type DefaultRequestLogRecord = {
  method: string;
  headers: Record<string, string>;
  body?: any;
  query?: Record<string, string>;
};

...the call order is preserved.

If you want to create a different request record you can do so by providing a custom requestLogger:

import { createMSWInspector, defaultRequestLogger } from 'msw-inspector';

const mswInspector = createMSWInspector({
  requestLogger: async (req) => {
    // Optionally use the default request mapper to get the default request log
    const defaultRecord = await defaultRequestLogger(req);

    return {
      myMethodProp: req.method,
      myBodyProp: defaultRecord.body,
    };
  },
});

getRequests Options

getRequests accepts an optional options object

await mswInspector.getRequests(string, {
  debug: boolean, // Throw debug error when no matching requests found (default: true)
});

Todo

  • Consider listening to network layer with @mswjs/interceptors and make MSW inspector usable in non-msw projects
  • Consider optionally returning requests not intercepted by msw (request:start/ request:match)