【发布时间】:2019-12-16 00:36:46
【问题描述】:
我是 Mocha 的新手,我一直在努力测试一个使用 Web 服务生成的令牌的函数。测试通过,但最后抛出错误。问题似乎与 Async/Await 函数有关。
如果我注释掉 .end 函数,则测试通过。 调试我可以看到 res.status 是 500,这意味着 await 不起作用...
我的测试文件代码如下:
var supertest = require("supertest");
var should = require("should");
const getToken = require("./getToken");
var server = supertest.agent("http://localhost:3000");
// Testing alarmStatusController
//
describe("Get Alarm Status", () => {
it("should return a json file and 200 if token valid", async () => {
let token = await getToken.getValidToken();
server
.get("/api/node/path")
.set('Authorization', 'Bearer ' + token)
.expect("Content-type", /json/)
.expect(200)
.end(function (err, res) {
res.status.should.equal(200);
res.body.message.should.equal('Alarms fetched successfully');
});
});
});
测试结果是:
Get Alarm Status
√ should return a json file and 200 if token valid (38ms)
1 passing (38ms)
C:\Dev\Globalwatch3\WebServices\GlobalwatchApi\node_modules\should\cjs\should.js:254
throw new AssertionError(params);
^
AssertionError: expected 500 to be 200
at Assertion.fail (C:\Dev\Globalwatch3\WebServices\GlobalwatchApi\node_modules\should\cjs\should.js:275:17)
at Assertion.value (C:\Dev\Globalwatch3\WebServices\GlobalwatchApi\node_modules\should\cjs\should.js:356:19)
at Test.<anonymous> (C:\Dev\Globalwatch3\WebServices\GlobalwatchApi\test\alarmStatus_test.js:29:39)
at Test.assert (C:\Dev\Globalwatch3\WebServices\GlobalwatchApi\node_modules\supertest\lib\test.js:181:6)
at localAssert (C:\Dev\Globalwatch3\WebServices\GlobalwatchApi\node_modules\supertest\lib\test.js:131:12)
at C:\Dev\Globalwatch3\WebServices\GlobalwatchApi\node_modules\supertest\lib\test.js:128:5
at Test.Request.callback (C:\Dev\Globalwatch3\WebServices\GlobalwatchApi\node_modules\superagent\lib\node\index.js:728:3)
at parser (C:\Dev\Globalwatch3\WebServices\GlobalwatchApi\node_modules\superagent\lib\node\index.js:916:18)
at IncomingMessage.res.on (C:\Dev\Globalwatch3\WebServices\GlobalwatchApi\node_modules\superagent\lib\node\parsers\json.js:19:7)
at IncomingMessage.emit (events.js:203:15)
at endReadableNT (_stream_readable.js:1129:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
希望有人可以帮助... 谢谢
【问题讨论】:
-
server.end是与callback的异步函数。因此,您的测试用例在您致电server.end后结束,而不是等待它完成。您需要在测试中使用done。
标签: node.js async-await mocha.js