1

I'm using supertest to implement a batch of canary tests for a quirky Web API that I don't control. One of the API's quirks consists of returning a plaintext string in a response that declares the Content-Type to be application/json.

This particular combination of factors leads supertest to throw the following error:

     SyntaxError: Unexpected token s in JSON at position 0
      at JSON.parse (<anonymous>)
      at Stream.res.on (node_modules/superagent/lib/node/parsers/json.js:11:35)
      at Unzip.unzip.on (node_modules/superagent/lib/node/unzip.js:55:12)
      at endReadableNT (_stream_readable.js:1064:12)
      at _combinedTickCallback (internal/process/next_tick.js:138:11)
      at process._tickCallback (internal/process/next_tick.js:180:9)

Does anyone know if there is any way to disable parsing the response body?

RAM
  • 2,257
  • 2
  • 19
  • 41

1 Answers1

4

I had the same problem as you, and I finally figured out a solution by looking into the superagent library (that as pretty much the same API). So here's how I solved it:

const { body, status } = await request(app)
  .get("/api/custom_path")
  // Disable automatic JSON parsing
  .buffer(true)
  .parse((res, cb) => {
    let data = Buffer.from("");
    res.on("data", function(chunk) {
      data = Buffer.concat([data, chunk]);
    });
    res.on("end", function() {
      cb(null, data.toString());
    });
  });
Unknown
  • 41
  • 2