Created
August 1, 2025 12:55
-
-
Save rcollette/cf05ed47a796f0de578887bc034948a6 to your computer and use it in GitHub Desktop.
Mock Service Worker Post Expectation with Sinon
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // msw-utils.ts | |
| import { rest, RestHandler } from 'msw' | |
| import { afterEach } from 'vitest' | |
| import sinon from 'sinon' | |
| /** | |
| * Creates an MSW POST handler that will throw in afterEach | |
| * if the actual request body doesn’t deep-equal the expected one, | |
| * using Sinon for comparison. | |
| */ | |
| export function createPostExpectation<T>( | |
| url: string | RegExp, | |
| expectedBody: T, | |
| responseResolver = (_req, ctx) => ctx.status(200) | |
| ): RestHandler { | |
| let mismatch: { actual: any } | null = null | |
| const handler = rest.post(url, async (req, res, ctx) => { | |
| const actual = await req.json() | |
| let equal = true | |
| try { | |
| // Throws if actual and expectedBody are not deeply equal | |
| sinon.assert.deepEqual(actual, expectedBody) | |
| } catch { | |
| equal = false | |
| } | |
| if (!equal) { | |
| mismatch = { actual } | |
| } | |
| return res(responseResolver(req, ctx)) | |
| }) | |
| afterEach(() => { | |
| if (mismatch) { | |
| throw new Error( | |
| `POST ${url} request body mismatch:\n` + | |
| ` expected: ${JSON.stringify(expectedBody)}\n` + | |
| ` actual: ${JSON.stringify(mismatch.actual)}` | |
| ) | |
| } | |
| }) | |
| return handler | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment