How to avoid timeouts in mocha testcases?

Anupam Jakhar picture Anupam Jakhar · Apr 28, 2016 · Viewed 7.9k times · Source

Here I am attaching my code, I am passing done callback and using supertest for request. Since I am using assert/expect in my testcase inside request.end block why I need to worry about timeout? What is mistake I am making here.

it('should get battle results ', function(done) {
    request(url)
      .post('/compare?vf_id='+vf_id)
      .set('access_token',access_token)
      .send(battleInstance)
      .end(function(err, res){  // why need timeout
        if (err) return done(err);
        console.log(JSON.stringify(res.body));
        expect(res.body.status).to.deep.equal('SUCCESS');
        done();
      });
 });

Testcase results following response: Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.

If I am running my testcases with mocha command then its show this error while If I am running test mocha --timeout 15000 then testcase is passing correctly. But I want to avoid timeout, How can I do that?

Answer

robertklep picture robertklep · Apr 28, 2016

If I am running my testcases with mocha command then its show this error while If I am running test mocha --timeout 15000 then testcase is passing correctly. But I want to avoid timeout, How can I do that?

You can't avoid timeouts, since it looks like you're testing a remote service. If, for whatever reason, the request to that service takes a long time, you will run into timeouts.

You can tell Mocha to disable for timeout checking by setting the timeout to 0, but that's probably also not ideal because it may cause each test case to take an excessive amount of time.

As an alternative, you can mock request (which I assume is superagent) so you can control the entire HTTP request/response flow, but since it looks like you're testing a remote service (one which you have no control over) that would make this particular test case moot.