A non-invasive `when-then` style API for MSW.
MSW is a brilliant tool for mocking, but is missing a few things to make it perfect for testing. msw-when-then aims to help with that.
- Succinct
when-then
style Api - Mock Chaining
- Implicitly assert request data is correct
- Support for both Rest and GraphQL requests
npm install msw-when-then
import { whenThen, get, ok } from "msw-when-then";
const { when } = whenThen(server, rest);
when(get("https://some.url")).thenReturn(ok({ foo: "bar" }));
Familiar chaining pattern, the responses are return in order with the last response returned for all subsequent requests.
import { get, badRequest, ok } from "msw-when-then";
when(get("https://some.url"))
.thenReturn(badRequest({ response: "first request" }))
.thenReturn(ok({ response: "subsequent requests" }));
Sometimes you need to take things into your own hands. We expose the original MSW resolver function, so you can do whatever you like. See MSW Docs for more details.
import { get } from "msw-when-then";
when(get("https://some.url")).then((req, res, ctx) => {
// Any additional logic here
return res(ctx.status(400), ctx.json({ response: "last response" }));
});
Mocking APIs is great, but how can we ensure our app is sending the right data? We can do this by specifying the expected request data when mocking.
Note: The id
key in the withParams
here matches the :id
argument in the post
url
import { post, request, withBody, withHeaders, withParams, ok } from "msw-when-then";
when(post("https://some.url/:id")).thenReturnFor(
request(
withBody({ foo: "bar" }),
withHeaders({ "content-type": "application/json" }),
withParams({ id: "expected-id" })
),
ok({ response: "success" })
);