【发布时间】:2017-06-23 10:36:16
【问题描述】:
节点 7.4.0 / express 4.14.0 / typescript 2.1.5 /m 3..1.2 / chai 3.5.0 / chai-http 3.0.0
我正在尝试使用 Mocha/Chai 测试未找到的资源,但在运行应用程序时失败并显示 404 错误
HeroRouter.ts
....
/**
* GET one hero by id
*/
public getOne(req: Request, res: Response, next: NextFunction) {
let query = parseInt(req.params.id);
let hero = Heroes.find(hero => hero.id === query);
if (hero) {
res.status(200)
.send({
message: 'Success',
status: res.status,
hero
});
}
else {
res.status(404)
.send({
message: 'No hero found with the given id.',
status: res.status
});
}
}
运行会显示如下日志:
$ http localhost:3000/api/v1/heroes/-32
HTTP/1.1 404 Not Found
Connection: keep-alive
Content-Length: 46
Content-Type: application/json; charset=utf-8
Date: Mon, 06 Feb 2017 12:53:34 GMT
ETag: W/"2e-W+nFWN7hcnJDQ4ZwWcRkpQ"
X-Powered-By: Express
{
"message": "No hero found with the given id."
}
但是尝试编写测试会失败:
herotest.ts describe('GET api/v1/heroes/:id', () => {
it('should respond with Not Found', () => {
return chai.request(app).get('/api/v1/heroes/-32')
.then(res => {
expect(res.status).to.equal(404);
});
});
});
npm 测试失败
GET /api/v1/heroes/-32 404 1.209 ms - 46
1) should respond with Not Found
1 failing
1) GET api/v1/heroes/:id should respond with Not Found:
Error: Not Found
at Test.Request.callback (node_modules/superagent/lib/node/index.js:626:17)
at node_modules/superagent/lib/node/index.js:795:18
at IncomingMessage.<anonymous> (node_modules/superagent/lib/node/parsers/json.js:16:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
已解决。根据谢尔盖的回答 -
it('should respond with Not Found', () => {
return chai.request(app).get('/api/v1/heroes/-32')
.catch(function (res) {
expect(res.status).to.equal(404);
});
});
【问题讨论】:
标签: node.js express tdd mocha.js chai