【问题标题】:How to configure supertest to not parse the response body?如何配置 supertest 不解析响应正文?
【发布时间】:2019-09-02 08:28:14
【问题描述】:

我正在使用 supertest 为我无法控制的古怪 Web API 实施一批金丝雀测试。 API 的一个怪癖包括在将Content-Type 声明为application/json 的响应中返回一个纯文本字符串。

这种特殊的因素组合导致 supertest 抛出以下错误:

     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)

有谁知道是否有任何方法可以禁用解析响应正文?

【问题讨论】:

    标签: supertest superagent web-api-testing


    【解决方案1】:

    我遇到了和你一样的问题,我终于通过查看 superagent 库(几乎相同的 API)找到了解决方案。 所以我是这样解决的:

    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());
        });
      });
    

    【讨论】:

      猜你喜欢
      • 2013-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多