node.jsmocha.jschai

In mocha testing while calling asynchronous function how to avoid the timeout Error: timeout of 2000ms exceeded


In my node application I'm using mocha to test my code. While calling many asynchronous functions using mocha, I'm getting timeout error (Error: timeout of 2000ms exceeded.). How can I resolve this?

var module = require('../lib/myModule');
var should = require('chai').should();

describe('Testing Module', function() {

    it('Save Data', function(done) {

        this.timeout(15000);

        var data = {
            a: 'aa',
            b: 'bb'
        };

        module.save(data, function(err, res) {
            should.not.exist(err);
            done();
        });

    });


    it('Get Data By Id', function(done) {

        var id = "28ca9";

        module.get(id, function(err, res) {

            console.log(res);
            should.not.exist(err);
            done();
        });

    });

});

Solution

  • You can either set the timeout when running your test:

    mocha --timeout 15000
    

    Or you can set the timeout for each suite or each test programmatically:

    describe('...', function(){
      this.timeout(15000);
    
      it('...', function(done){
        this.timeout(15000);
        setTimeout(done, 15000);
      });
    });
    

    For more info see the docs.