Search code examples
asynchronoustestingmocha.jssupertest

Testing Mocha/supertest/expect MEAN-stack HTTP Request 4 seconds delay done


I am testing a HTTP Request in MEAN-Stack with Mocha/supertest/expect library, that takes 4 seconds to return:

it('should return product data', (done) => {
    request(app)
    .get('/P/Product')
    .expect(200)
    .expect((res) => {
        expect(res.body[0]._id).toEqual('123456789')
    })
    .end(done);
});

The function should execute the "done" callback at the end, after the HTTP Request finished. But I am getting error:

1) should return product data:
     Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a
Promise, ensure it resolves. 

I think it works with unnested expect-calls. How would I do it with nested expect-calls inside other expect-calls, like in the example abouve?


Solution

  • Maybe the response time from the request is too high and causing Mocha's default 2 second test timeout to happen. Possibly try a cURL to the url from CLI to see what timing you get back or up the mocha test time threshold for the test.

    describe('testing', function() {
        // This applies the timeout of 5 seconds to each test.
        this.timeout(5000);
    
        it('should return product data', function() {
           // This applies a timeout of 5 seconds for this test only
           this.timeout(5000);
           request(app)
               .get('/P/Product')
               .expect(200)
               .expect((res) => {
                    expect(res.body[0]._id).toEqual('123456789')
               })
               .end(done);
           });
    });
    

    Another way would to use the promise approach if you thing the chain of expect calls is causing timeout issues.

    it('should return product data', () => {
       request(app)
       .get('/P/Product')
       .then((res) => {
           expect(res.status).to.equal(200);
           expect(res.body[0]._id).to.equal('123456789');
       })
    });