Skip to content

Instantly share code, notes, and snippets.

@rcollette
Created August 1, 2025 12:55
Show Gist options
  • Select an option

  • Save rcollette/cf05ed47a796f0de578887bc034948a6 to your computer and use it in GitHub Desktop.

Select an option

Save rcollette/cf05ed47a796f0de578887bc034948a6 to your computer and use it in GitHub Desktop.
Mock Service Worker Post Expectation with Sinon
// 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