In my node application i'm using mocha to test my code.While calling many asynchronous function 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();
});
});
});
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.
I find that the "solution" of just increasing the timeouts obscures what's really going on here, which is either
The problem is that mocha doesn't (always) catch thrown errors in the async code. There has been a lot of discussion on how to fix this in Mocha (see this issue), but there doesn't seem to be a consensus on how it could be done in a clean way that won't have messy side effects.
In general, the cleanest way (but ugliest) way of dealing with this problem is to wrap your code with a try/catch and pass any exceptions to the done handler.
it('should not fail', function (done) {
myAsyncFn(function (err, result) {
try { // boilerplate to be able to get the assert failures
assert.ok(true);
assert.equal(result, 'bar');
done();
} catch (x) {
done(x);
}
});
});
Other than that I suggest you pick up the advice on starting to use test stubs for network calls to make tests pass without having to rely on a functioning network. Using Mocha, Chai and Sinon the tests might look something like this
describe('api tests normally involving network calls', function() {
beforeEach: function () {
this.xhr = sinon.useFakeXMLHttpRequest();
var requests = this.requests = [];
this.xhr.onCreate = function (xhr) {
requests.push(xhr);
};
},
afterEach: function () {
this.xhr.restore();
}
it("should fetch comments from server", function () {
var callback = sinon.spy();
myLib.getCommentsFor("/some/article", callback);
assertEquals(1, this.requests.length);
this.requests[0].respond(200, { "Content-Type": "application/json" },
'[{ "id": 12, "comment": "Hey there" }]');
expect(callback.calledWith([{ id: 12, comment: "Hey there" }])).to.be.true;
});
});
See the Sinon docs for more info.