mardi 26 juin 2018

Testing API error with supertest and jest fails even though response is correct

I'm using jest 23.1.0 and supertest 3.1.0. I'm writing some tests for my backend and things have been going ok, however for a specific case of a specific route, the test is failing even though the response object seems to contain the right information. The test is to check if a parameter is valid JSON, and is as such:

describe('GET /graph', () => {
    it('invalid JSON', (done) => {
        request(app)
            .get('/graph')
            .set('Accept', 'application/json')
            .expect('Content-Type', /json/)
            .expect(415)
            .then(done);
        });
});

In this case I'm not actually sending any parameter at all, but even if I do send some invalid JSON the issue is the same. Both cases trigger the same backend check anyway, which is:

module.exports = (req, res, next) => {

    let dataParameters;
    try {
        dataParameters = JSON.parse(req.query.dataParameters);
    }
    catch(error) {
        return(res.status(415).send({
            message: "Request parameters are not a valid JSON object",
            other: `${error.name} - ${error.message}`
        }));
    }
    ...

When I run jest, the test fails and the output to the console is this:

  GET /graph
    ✕ invalid JSON (6ms)

  ● GET /graph › invalid JSON

    Failed: Object {
      "header": Object {
        "connection": "close",
        "content-length": "125",
        "content-type": "application/json; charset=utf-8",
        "date": "Tue, 26 Jun 2018 13:58:48 GMT",
        "etag": "W/\"7d-GGhtZ8CfzWfmANZW28JTNC5bNjU\"",
        "x-powered-by": "Express",
      },
      "req": Object {
        "data": undefined,
        "headers": [Object],
        "method": "GET",
        "url": "http://127.0.0.1:35875/graph",
      },
      "status": 415,
      "text": "{\"message\":\"Request parameters are not a valid JSON object\",\"other\":\"SyntaxError - Unexpected token u in JSON at position 0\"}",
    }

      at Env.fail (node_modules/jest-jasmine2/build/jasmine/Env.js:537:34)

So looking at the object jest prints it seems the route is returning the right HTTP status and message, however instead of supertest handling that, the actual test itself is failing. I use the same response format and testing technique for testing other API errors and this doesn't happen. I've tried changing the request parameters, error codes and various other things but to no avail.

Aucun commentaire:

Enregistrer un commentaire