3

I am currently using Nock and would like to replace it with Mock Service Worker.
With Nock I am able to match the stringified request body with the provided buffer:

const request = nock(hostname)
      .post('/api/instance', Buffer.from(arrayBuffer))
      .reply(201, json);

I have not figured out how to get the same result with mws because the request body and the buffer are not equal. Can someone help me?
Thanks.

AmD
  • 399
  • 2
  • 12

1 Answers1

0

AmD.

First things first, request matching in MSW is intentionally limited only to the method and URL matching. That does not mean, however, that you cannot implement a more complex matching logic when needed. You can write it in your request handler:

rest.post('/api/instance', (req, res, ctx) => {
  if (someMatchCriteria) {
    return res(ctx.text('hello world'))
  }
})

For example, in this handler only the requests that match someMatchCriteria will use the mocked response. All the other (non-matching) requests will be passthrough.

You can access the text request body via req.body. MSW converts all request bodies to plain text in order to sent it over the message channel to the worker. You can convert that text to Buffer and compare them yourself.

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'))
  }
})

You may use other means to convert text to buffer. If the buffer lengths/content don't match, it likely means the conversion solution you're using does not produce the correct buffer representation of the request body string.

kettanaito
  • 974
  • 5
  • 12