AmD.
When it comes to request matching in MSW, the focus is on method and URL matching. However, if you need a more intricate matching logic, you have the flexibility to implement it within your request handler:
rest.post('/api/instance', (req, res, ctx) => {
if (someMatchCriteria) {
return res(ctx.text('hello world'))
}
})
For instance, in the above handler, only requests that meet the criteria specified by someMatchCriteria
will trigger the mocked response. Other requests that don't match will pass through.
The request body can be accessed as plain text using req.body
. MSW converts all request bodies for transmission over the message channel to the worker. You can then convert that text into a buffer to make comparisons manually:
rest.post('/api/instance', (req, res, ctx) => {
const encoder = new TextEncoder()
const text = req.body
const buffer = encoder.encode(text)
if (buffer === expectedBuffer) {
return res(ctx.text('mocked response'))
}
})
There are various methods available for converting text to buffer. If there's an issue with mismatched lengths or content, it could indicate that the chosen conversion method is not accurately representing the request body string as a buffer.