3

我正在使用 mocha、chai 和 chai-http 来测试我的简单 API,该 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)

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

  • 有人说我不应该测试我不拥有的代码:这很有意义,但是我应该测试什么,因为它只是一个简单的集成服务?
  • 有人说我应该模拟外部 api 结果:但我不会测试任何东西,因为它只是一个集成。

我该如何解决这个问题?

提前致谢。

4

1 回答 1

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', () => {
     })
  })
})
于 2018-05-10T18:02:13.917 回答