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

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

我正在为我的 api 创建集成测试并 运行 出现以下错误:

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

我知道这个问题已被问过几次,但答案并没有帮助我解决这个问题。有问题的测试是测试一个 POST 路由,并且正在调用 done 回调:

it('should create a transaction', function(done) {
    request(app)
      .post('/api/transactions')
      .send({
        name: 'Cup of coffee',
        amount: 2.50,
        date: '2016-11-17T17:08:45.767Z'
      })
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      .expect(201)
      .end(function(err, resp) {
        expect(resp.body).to.be.an('object');
        done();
      })
  })

post路线如下:

.post(function (req, res) {
    var transaction = new Transaction()
    transaction.name = req.body.name
    transaction.amount = req.body.amount
    transaction.date = req.body.date

    transaction.save(function (err) {
      if (err) {
        res.send(err)
      }
      res.json(transaction)
    })
  })

交易的猫鼬模式是:

var mongoose = require('mongoose')
var Schema = mongoose.Schema

var TransactionsSchema = new Schema({
  name: String,
  amount: Number,
  date: { type: Date, default: Date.now }
}, {
  collection: 'transactions'
})

module.exports = mongoose.model('Transactions', TransactionsSchema)

有什么想法吗?谢谢:)

在您的测试中,您可以指定测试 timeout

it('should create a transaction', function(done) {
    // Specify a timeout for this test
    this.timeout(30000);

    request(app)
      .post('/api/transactions')
      .send({
        name: 'Cup of coffee',
        amount: 2.50,
        date: '2016-11-17T17:08:45.767Z'
      })
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      .expect(201)
      .end(function(err, resp) {
        expect(resp.body).to.be.an('object');
        done();
      })
  });