【问题标题】:mocha async test is timing outmocha 异步测试超时
【发布时间】:2020-03-26 12:22:33
【问题描述】:

您好,我是使用 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"
}

【问题讨论】:

标签: node.js unit-testing mocha.js


【解决方案1】:

为什么不尝试增加超时时间(毫秒),测试运行缓慢是正常的,尤其是在测试网络请求时。

package.json

"test": "mocha --timeout 10000"

【讨论】:

  • 是的,我能够通过删除 mongoDB 连接的测试来解决它。我认为是关闭连接导致其他测试失败。
  • @rfguy 很酷,也许您可​​以更新您的问题或自己回答?它没有得到回答,使 StackOverflow 变得混乱(充满了未回答的问题)
【解决方案2】:

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

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

【讨论】:

  • 是的,端点返回响应。我会玩弄超时。
  • 很高兴听到!如果它解决了您的问题,请不要忘记选择最合适的回复,以帮助将来找到您问题的人:)
  • 即使延长了超时时间,我仍然遇到同样的错误。
  • 很奇怪。测试结果说明了什么?您能否将端点的代码添加到您的问题中?那里可能会发生一些时髦的事情。
  • 我刚刚在原始帖子中添加了来自端点的响应。
【解决方案3】:

对此不确定。但据我回忆,混合 Promises 和回调样式 (done-callback) 可能会在 mocha 中导致此类问题。

尝试仅使用 Promise:

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

【讨论】:

    【解决方案4】:

    问题是这个测试: 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);
        });
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2017-02-26
      • 2014-02-08
      • 1970-01-01
      • 1970-01-01
      • 2012-08-22
      • 2018-03-06
      • 2015-10-23
      • 2012-09-29
      • 1970-01-01
      相关资源
      最近更新 更多