MSW inspector
![Test coverage report](https://coveralls.io/repos/github/toomuchdesign/msw-inspector/badge.svg?branch=master)
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 request is saved as a function mock call retrievable by URL. This allows elegant assertions against request information like method
, headers
, body
, query
.
Example
This example uses Jest, but MSW inspector integrates with any testing framework.
import { createMSWInspector } from 'msw-inspector';
import { server } from '@/mocks/server';
const mswInspector = createMSWInspector({
mockSetup: server,
mockFactory: () => jest.fn(),
});
beforeAll(() => {
mswInspector.setup();
});
beforeEach(() => {
mswInspector.clear();
});
afterAll(() => {
mswInspector.teardown();
});
describe('My test', () => {
it('My test', async () => {
expect(mswInspector.getRequests('http://my.url/path')).toHaveBeenCalledWith(
{
method: 'GET',
headers: {
'my-header': 'value',
},
body: {
'my-body': 'value',
},
query: {
'my-query': 'value',
},
}
);
});
});
API
createMSWInspector
Create a MSW inspector
instance bound to a specific msw
SetupServerApi or SetupWorkerApi instance:
import { createMSWInspector } from 'msw-inspector';
createMSWInspector({
mockSetup,
mockFactory,
});
getRequests
Returns a mocked function containing all the calls intercepted for the given absolute url:
mswInspector.getRequests('http://my.url/path');
Each intercepted request calls the matching mocked function with the following payload:
type CallPayload = {
method: string;
headers: Record<string, string>;
body?: any;
query?: Record<string, string>;
};
Todo
- Consider a better name for
getRequests
- Consider listening to network layer with
@mswjs/interceptors
and make MSW inspector usable in non-msw
projects - Consider accepting a function to customize requests mapping and payload