使用supertest抛出错误将querystring传递给api:ECONNREFUSED:连接被拒绝

时间:2019-05-27 03:43:22

标签: node.js mocha chai supertest

describe("Test report api ", function() {
    it("should get the report for given date range", function(done) {
      this.timeout(100000);
      agent
        .get("rbac/aa/contentful/getReport")
        .query({ startDate: "1557759433000", endDate: "1558450633000" })
        .expect(200)
        .end(function(err, res) {
          console.log("err:", err);
          console.log("response:", res);
          done();
        });
    });
  });

错误

ECONNREFUSED: Connection refused
    at Test.assert (/Users/premkumarsrinivasan/Documents/repositories/GIS_lilly_us_hub/node_modules/supertest/lib/test.js:165:15)
    at Server.localAssert (/Users/premkumarsrinivasan/Documents/repositories/GIS_lilly_us_hub/node_modules/supertest/lib/test.js:131:12)
    at Object.onceWrapper (events.js:273:13)
    at Server.emit (events.js:182:13)
    at emitCloseNT (net.js:1618:8)
    at process._tickCallback (internal/process/next_tick.js:63:19)
response: undefined

1 个答案:

答案 0 :(得分:0)

传递给agent.get()方法的网址不正确。

更改为:

agent.get("/rbac/aa/contentful/getReport")

例如

app.js

const express = require("express");
const app = express();

app.get("/rbac/aa/contentful/getReport", (req, res) => {
  res.sendStatus(200);
});

module.exports = app;

app.test.js

const app = require("./app");
const request = require("supertest");
const agent = request(app);

describe("Test report api ", function() {
  it("should get the report for given date range", function(done) {
    this.timeout(100000);
    agent
      .get("/rbac/aa/contentful/getReport")
      .query({ startDate: "1557759433000", endDate: "1558450633000" })
      .expect(200)
      .end(function(err, res) {
        if (err) {
          return done(err);
        }
        done();
      });
  });
});

具有覆盖率报告的集成测试结果:

 Test report api 
    ✓ should get the report for given date range


  1 passing (31ms)

-------------|----------|----------|----------|----------|-------------------|
File         |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-------------|----------|----------|----------|----------|-------------------|
All files    |    93.33 |       50 |      100 |    93.33 |                   |
 app.js      |      100 |      100 |      100 |      100 |                   |
 app.test.js |       90 |       50 |      100 |       90 |                14 |
-------------|----------|----------|----------|----------|-------------------|

源代码:https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/56319424