Error: timeout of XX ms exceeded. Ensure the done() callback is being..supertest+express()

2.5k views Asked by At

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;
        ......
    }

};
1

There are 1 answers

2
Wilson On

I have created an example using express, mocha, and supertest.

This is my app.js:

var express = require('express');
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.post('/api/products', function(req, res) {
  var product = req.body;
  res.send({
    message: 'product was saved succesfully.',
    product: product
  });
});

app.listen(4040, function() {
  console.log('server up and running at 4040');
});

module.exports = app;

And this is my test.js:

var request = require('supertest');
var app = require('./app.js');

describe('Test Products', function() {
  it('should create a product', function(done) {
    request(app)
      .post('/api/products')
      .send({name: 'chairman'})
      .end(function (err, res) {
        console.log(res.text);
        done();
      });
  });
});