I am trying to test apis for my node server(using express) via mocha+supertest. I have a post API like in my app.js as :
app.post('/product/createProduct',routes.createProduct);
In routes, this api looks like:
functions.createProduct = function(req,res){
var body ="";
var jsonObj={};
console.log('create product called..');
req.on('data',function(chunk){
body += chunk;
});
req.on('end',function(){
jsonObj = JSON.parse(body);
createProductAsync(req,jsonObj,res);
});
which takes json having product info in the request body. This api is working fine with postman but when i am calling the same using supertest + mocha `
it('should create a new product', function (done) {
var req = supertest(app).post('/product/createProduct');
agent.attachCookies(req);
req.send({name:"someName"});
req.expect(404)
req.end(function(err,res){
if(err) throw(err);
done();
})
});`
i am getting error for time exceeded.
`Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test`
i have already tried --timeout option or this.setTimeout but that also is not helping. Any clue? Workout i am using
functions.createProduct = function(req,res){
var body ="";
var jsonObj={};
console.log('create product called..');
req.on('data',function(chunk){
body += chunk;
});
req.on('end',function(){
jsonObj = JSON.parse(body);
......
});
if(DEBUG){
/*using supertest, req.body is not received in chunks,hence .req.end event is never transmitted.*/
console.log('debug mode');
jsonObj = req.body;
......
}
};
I have created an example using express, mocha, and supertest.
This is my
app.js
:And this is my
test.js
: