gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 06:34:25 24 4
gpt4 key购买 nike

我正在使用 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 测试”的结果:

  /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 的调用并测试您的应用在调用外部 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', () => {
})
})
})

关于node.js - 如何测试在 Node 中调用另一个外部 API 的 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50275188/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com