user762579
user762579

Reputation:

Node/Express API test Not Found failing

node 7.4.0 / express 4.14.0 / typescript 2.1.5 /m 3..1.2 / chai 3.5.0 / chai-http 3.0.0

I am trying to test a resource not found using Mocha/Chai but it's failing when running the app displays the 404 error

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
                });
        }
    }

Running will display the following log :

$ 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."
}

BUT trying to write test will fail :

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 test FAILING

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)

SOLVED. as per Sergey's answer -

it('should respond with Not Found', () => {
    return chai.request(app).get('/api/v1/heroes/-32')
        .catch(function (res) {
            expect(res.status).to.equal(404);
        });
});

Upvotes: 0

Views: 1790

Answers (1)

Sergey Lapin
Sergey Lapin

Reputation: 2693

As the status code indicates that request was not successful, superagent (where stack trace points to) treats this like an error: source. Your then branch of promise is never executed, leaving promise rejection uncaught by your code.

Looks like this behavior was fixed in both chai-http and superagent, but not yet released to npm for the former: https://github.com/chaijs/chai-http/issues/75

Upvotes: 1

Related Questions