摩卡异步测试超时

时间:2019-12-01 20:18:34

标签: node.js unit-testing mocha

嗨,我是Mocha测试的新手,更不用说异步测试了。运行此测试时,我不断收到以下错误。我花了很多时间在网络上研究分辨率,但是没有运气。

错误:超时超过2000毫秒。对于异步测试和挂钩,请确保调用了“ done()”;如果返回了Promise,请确保它可以解决。

it('Should fail to create new user due to missing email', (done) => {
  const user_empty_email = {
    name: "First Name",
    email: "",
    password: "password",
    isAdmin: false
  }
  chai.request(app).post('/v1/users')
    .send(user_empty_email)
    .then((res) => {
      expect(res).to.have.status(400);
      done();
    }).catch(done)
})

以下是示例响应,我正在获取/ v1 / users

{
  "user": {
      "_id": "5de4293d3501dc21d2c5293c",
      "name": "Test Person",
      "email": "testemail@gmail.com",
      "password": "$2a$08$8us1C.thHWsvFw3IRX6o.usskMasZVAyrmccTNBjxpNQ8wrhlBt6q",
      "isAdmin": false,
      "tokens": [
          {
              "_id": "5de4293d3501dc21d2c5293d",
              "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZGU0MjkzZDM1MDFkYzIxZDJjNTI5M2MiLCJpYXQiOjE1NzUyMzM4NTN9.mi4YyYcHCvdYrl7OuI5eDwJ8xQyKWDcqgKsXRYtn0kw"
          }
      ],
      "__v": 1
  },
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZGU0MjkzZDM1MDFkYzIxZDJjNTI5M2MiLCJpYXQiOjE1NzUyMzM4NTN9.mi4YyYcHCvdYrl7OuI5eDwJ8xQyKWDcqgKsXRYtn0kw"
}

4 个答案:

答案 0 :(得分:2)

为什么不尝试以(ms)为单位增加超时,这是测试运行缓慢的正常现象,尤其是在测试网络请求时。

package.json

IRule

答案 1 :(得分:1)

您的端点是否有可能实际花费超过2秒的时间来运行?如果是这样,您可能要在运行Mocha时增加超时:Change default timeout for mocha

此外,您的端点是否返回响应?如果没有,增加超时将无济于事。您可以将/v1/users端点的代码添加到您的问题中以研究这种可能性吗?

答案 2 :(得分:1)

对此不确定。但是据我记得,将Promises和回调样式(done-callback)混合使用会在摩卡咖啡中引起此类问题。

尝试仅使用Promises:

  • 从测试中删除所有done
  • 实际上是return的承诺(return chai.request...

答案 3 :(得分:0)

问题是这个测试: mongoDB-connect.js

它在其他人之前跑了。 mongoDB连接被关闭,导致其他测试超时。当我删除关闭命令时,所有测试均按预期通过。

"use strict";
// NPM install mongoose and chai. Make sure mocha is globally
// installed
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const chai = require('chai');
const expect = chai.expect;
// Create a new schema that accepts a 'name' object.
// 'name' is a required field
const testSchema = new Schema({
  name: { type: String, required: true }
});

// mongoose connect options
var options = {
    useNewUrlParser: true,
    useUnifiedTopology: true
}

//Create a new collection called 'Name'
const Name = mongoose.model('Name', testSchema);
describe('Database Tests', function() {
  //Before starting the test, create a sandboxed database connection
  //Once a connection is established invoke done()
  before(function (done) {    
    // mongoose.connect('mongodb://localhost:27017',options);
    mongoose.connect('mongodb://ip/testDatabase',options);
    const db = mongoose.connection;
    db.on('error', console.error.bind(console, 'connection error'));
    db.once('open', function() {
      console.log('We are connected to test database!');
      done();
    });
  });
  describe('Test Database', function() {
    //Save object with 'name' value of 'Mike"
    it('New name saved to test database', function(done) {
      var testName = Name({
        name: 'Mike'
      });

      testName.save(done);
    });
    it('Dont save incorrect format to database', function(done) {
      //Attempt to save with wrong info. An error should trigger
      var wrongSave = Name({
        notName: 'Not Mike'
      });
      wrongSave.save(err => {
        if(err) { return done(); }
        throw new Error('Should generate error!');
      });
    });
    it('Should retrieve data from test database', function(done) {
      //Look up the 'Mike' object previously saved.
      Name.find({name: 'Mike'}, (err, name) => {
        if(err) {throw err;}
        if(name.length === 0) {throw new Error('No data!');}
        done();
      });
    });
  });
  //After all tests are finished drop database and close connection
  after(function(done){
    mongoose.connection.db.dropDatabase(function(){
      mongoose.connection.close(done);
    });
  });
});