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

3

我正在使用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)

我已经在许多论坛和网站上搜索过了:
  • 有些人说我不应该测试我不拥有的代码:这很有道理,但既然它只是一个简单的集成服务,那我应该测试什么呢?
  • 有些人说我应该模拟外部api的结果:但我将无法测试任何东西,因为它只是一个集成。
我该如何解决这个问题?
提前感谢。

你的应用程序中有一个名为/habitica的端点,还是它是第三方服务? - mandar.gokhale
是的,我的应用程序中有这个端点。该端点调用 Habitica API,这是第三方服务。 - André Maldonado
@AndréMaldonado 你解决问题了吗?如果是,你是如何解决的? - Slim
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', () => {
     })
  })
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接