如何测试在节点中调用另一个外部API的API

时间:2018-05-10 14:23:37

标签: node.js mocha chai chai-http

我正在使用mocha,chai和chai-http测试我的简单API,它将来自Slack的呼叫路由到Habitica,整合这两个服务。

我正在尝试创建测试,但我遇到了这个问题:当我调用我的API时,代码会在外部API调用之前返回。这是测试的代码:

var chai = require("chai");
var chaiHttp = require("chai-http");
var server = require("../src/app/index");
var should = chai.should();

chai.use(chaiHttp);

describe("/GET list", () => {
    it("it should return a list of user\'s tasks", (done) => {
        chai.request(server)
        .post("/habitica")
        .type("urlencoded")
        .send({text: "list"})
        .end((err, res) => {
            res.should.have.status(200);
            res.body.should.be.a("object");
            res.body.should.have.property("success").eql("true");
            done();
        });
    });
}); 

这是测试调用的代码:

app.post("/habitica", server.urlencodedParser, function(req, res) {
    if (typeof req.body !== "undefined" && req.body) {
        switch(req.body.text) {
            case "list":
                request({
                    url: GET_TASKS,
                    headers: { "x-api-user": process.env.HABITICA_USERID, "x-api-key": process.env.HABITICA_APITOKEN }
                }, function (apiError, apiResponse, apiBody) {
                    if (apiError) {
                        res.send(apiError);
                    } else {
                        res.send(apiBody);
                    }
                });
                break; 
            default: 
                res.send({
            "success": "false",
            "message": "Still working on tasks creation"
        });
        }
    }
});

此代码在调用Habitica之前返回任何值。这是“npm test”的结果:

  /GET list
    1) it should return a list of user's tasks


  0 passing (2s)
  1 failing

  1) /GET list
       it should return a list of user's tasks:
     Uncaught AssertionError: expected {} to have property 'success'
      at chai.request.post.type.send.end (test/app.js:17:34)
      at Test.Request.callback (node_modules/superagent/lib/node/index.js:706:12)
      at IncomingMessage.parser (node_modules/superagent/lib/node/index.js:906:18)
      at endReadableNT (_stream_readable.js:974:12)
      at _combinedTickCallback (internal/process/next_tick.js:80:11)
      at process._tickCallback (internal/process/next_tick.js:104:9)

我已经在很多论坛和网站上搜索过:

我该如何解决这个问题?

提前致谢。

1 个答案:

答案 0 :(得分:1)

你应该模拟对外部API的调用&测试应用程序在调用外部API后如何失败或成功时的行为。 您可以按如下方式测试不同的方案

describe("/GET list", () => {
  // pass req.body.text = 'list'
  describe("when task list is requested", () => {
     describe("when task list fetched successfully", () => {
        // in beforeEach mock call to external API and return task list
        it('returns tasks list in response', () => {
        })
     }),
     describe("when error occurs while fetching task list", () => {
       // in beforeEach mock call to external API and return error
       it('returns error in response', () => {
       })
     })
  }),
  // when req.body.text != 'list'
  describe("when task list is not requested", () => {
     it('returns error in response', () => {
     })
  })
})