【问题标题】:Getting "TypeError: object is not a function" when using supertest/superagent in forEach loop在 forEach 循环中使用 supertest/superagent 时出现“TypeError:对象不是函数”
【发布时间】:2015-03-04 21:07:48
【问题描述】:

我正在使用 supertest 按照相同的规则测试一组 URL。

var urls = [
    "https://www.example.com",
    "https://www.example2.com"
];

urls.forEach(function (url) {
    console.log('begin');
    request = request(url)
        .get('')
        .expect(200)
        .end(function (err, res) {
            // Check for something
        });
    console.log('end');
});

当数组中只有 1 个 URL 时,它工作得很好。但是,如果我添加第二个,则输出失败:

begin
end
begin

file.js:11
request = request(json)
^
TypeError: object is not a function

我的猜测是我不能让 1 个 supertest 实例运行两次,但我似乎找不到解决此问题的解决方案。任何帮助表示赞赏。

【问题讨论】:

    标签: javascript node.js supertest superagent


    【解决方案1】:

    这是因为你的赋值 request = request(url) 覆盖了请求函数。

    var urls = [
        "https://www.example.com",
        "https://www.example2.com"];
    
    urls.forEach(function (url) {
        console.log('begin');
        var r = request(url)
            .get('')
            .expect(200)
            .end(function (err, res) {
            // Check for something
        });
        console.log('end');
    });
    

    在第一次迭代中,request 指的是一个全局函数,但是当评估 request = request(url) 语句时,request 的值被更改为 request(url) 返回的值,所以在第二次迭代中 request 是不再是您期望的功能。

    【讨论】:

      【解决方案2】:

      更改以下内容

      request = request(url)
          .get('')
          .expect(200)
          .end(function (err, res) {
              // Check for something
          });
      

      requestVariable = request(url)
          .get('')
          .expect(200)
          .end(function (err, res) {
              // Check for something
          });
      

      【讨论】:

      • 任何时候,虽然我迟到了 2 分钟 :)
      猜你喜欢
      • 1970-01-01
      • 2015-09-27
      • 2014-03-06
      • 1970-01-01
      • 1970-01-01
      • 2020-04-29
      • 1970-01-01
      • 1970-01-01
      • 2021-04-19
      相关资源
      最近更新 更多