node.jstestingbuffernock

How to match a binary buffer request body with Nock?


I am new at Node/TypeScript and write a simple script to learn the language. I am using nock for tests to check my http post requests with RequestBodyMatcher. Currently, it's dummy (see below). Now I want to implement the matcher and actually check the request body.

const requestBodyMatcher = (body: any) => true; // todo: check the body !!!
nock('http://api.michael.com')
  .post('/myendpoint', requestBodyMatcher)
  .reply(200);

My request body is s binary buffer (some zipped data) but my requestBodyMatcher function is invoked with body:string rather than body:Buffer as I checked. Do you have any example of matching a binary buffer request body ?


Solution

  • As it's said in the comments RequestBodyMatcher receives a stringified request body, so I has to unstrigify it with Buffer.from and hex encoding:

    const requestBodyMatcher = (body: any) => {
      const buf = Buffer.from(body, 'hex')
      // check "buf" and return a boolean result
    };