2

I have a node app which exposes a simple REST api using express. It includes a GET endpoint which should return a JSON array of data from a mongo database. It works perfectly when tested from Postman.

api.get('/queries', (req, res) => {
    db.getQueries().then(docs => {
        res.json({ queries: docs });
    })
});

I'd like to programmatically test it so have set up a test using chai-http:

describe('When database contains zero queries', () => {
it('/GET queries should return 0 as the body length', (done) => {
    return chai.request(queriesApi).get('/queries').then((result) => {
        result.should.have.status(200);
        result.body.should.be.a('array');
        result.body.length.should.be.eql(0);
        done()
    });
});

});

However, during the test I get the error:

TypeError: res.json is not a function

at the point where the data has been retrieved in the GET handler and is ready to be sent back to the caller.

I'm unable to fathom the difference between testing this endpoint in Postman and via a unit test. I've stepped through the code and in both tests (Postman and unit) res is a ServerResponse and req is an IncomingMessage.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.