【问题标题】:Node/Express API test Not Found failing未找到节点/Express API 测试失败
【发布时间】: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


    【解决方案1】:

    由于状态码表明请求不成功,superagent(堆栈跟踪指向的位置)将此视为错误:source。你的then 承诺分支永远不会被执行,你的代码不会捕获承诺拒绝。

    看起来这种行为在 chai-http 和 superagent 中都已修复,但尚未针对前者发布到 npm:https://github.com/chaijs/chai-http/issues/75

    【讨论】:

    • @erwin 我刚刚添加了一个指向相关 gitbub 问题的链接
    猜你喜欢
    • 2018-04-21
    • 1970-01-01
    • 2017-06-24
    • 2016-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-15
    • 2017-11-29
    相关资源
    最近更新 更多