错误:超过XX毫秒的超时。确保done()回调正在...supertest + express()

时间:2015-06-26 08:24:53

标签: javascript node.js express mocha supertest

我正在尝试通过mocha + supertest测试我的节点服务器的api(使用express)。 我在 app.js 中有一个帖子API,如:

    app.post('/product/createProduct',routes.createProduct);

在路线中,这个api看起来像:

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

使json在请求正文中包含产品信息。这个api与邮递员一起工作正常,但是当我使用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();
            })
 });`

我在超出时间时遇到错误。

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

我已经尝试过--timeout选项或this.setTimeout,但这也没有帮助。任何线索? 我正在使用锻炼

    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 个答案:

答案 0 :(得分:0)

我使用express,mocha和supertest创建了一个例子。

这是我的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;

这是我的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();
      });
  });
});