GithubHelp home page GithubHelp logo

rickythefox / msw-inspector Goto Github PK

View Code? Open in Web Editor NEW

This project forked from toomuchdesign/msw-inspector

0.0 0.0 0.0 1.22 MB

Inspect requests intercepted by MSW

License: MIT License

TypeScript 100.00%

msw-inspector's Introduction

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:

// Full string match
await mswInspector.getRequests('http://my.url/path/foo');

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

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)

msw-inspector's People

Contributors

dependabot[bot] avatar toomuchdesign avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.