【问题标题】:simple GET request in mocha timeoutmocha超时中的简单GET请求
【发布时间】:2020-12-13 19:28:58
【问题描述】:

我有以下代码

const https = require("https");

it("wait for some result", function (done) {
  this.timeout(15000);
  const options = {
    hostname: "httpbin.org",
    path: "/get",
    headers: {
      Authorization: "bearer ",
    },
  };
  https.get(options, (resp) => {
    let data = "";
    // A chunk of data has been recieved.
    resp.on("data", (chunk) => {
      data += chunk;
      console.log(data);
    });
    // The whole response has been received. Print out the result.
    resp.on("end", () => {
      console.log(JSON.parse(data).explanation);
    });

    resp.on("error", (err) => {
      console.log("Error: " + err.message);
    });
    done();
  });
});

返回:

  1. 应在帖子中使用重定向响应: 错误:超过 15000 毫秒的超时。确保在此测试中调用了 done() 回调。

由于 mocha,我试图使这个异步,这就是我使用回调的原因。我什至在等待 15000 而不是默认的 2000ms。

此代码正常工作,只有 mocha 失败。 不知道如何解决这个问题。任何帮助表示赞赏。 提前致谢。

【问题讨论】:

  • 你试过把done放到resp.on("end")回调中吗?
  • @Yevhenii 是的,我得到了同样的结果

标签: javascript node.js rest https mocha.js


【解决方案1】:

尝试在您的请求对象上添加.end()

  const req = https.get(options, (resp) => {
    let data = "";
    // A chunk of data has been recieved.
    resp.on("data", (chunk) => {
      data += chunk;
      console.log(data);
    });
    // The whole response has been received. Print out the result.
    resp.on("end", () => {
      console.log(JSON.parse(data).explanation);
      done();
    });

    resp.on("error", (err) => {
      console.log("Error: " + err.message);
    });
  });
  req.end()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-14
    • 2021-03-12
    • 2019-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-25
    • 1970-01-01
    相关资源
    最近更新 更多