【问题标题】:Mocha beforeEach exceeds timeoutMocha beforeEach 超过超时
【发布时间】:2018-04-19 13:31:31
【问题描述】:

我正在尝试为使用 Express 和 MongoDB 制作的 REST API 设置测试。我想使用mocha、chai 和chai-http,但我遇到了一个奇怪的行为,似乎beforeEach 函数超过了超时,就像它永远不会被解决一样。我该如何解决这个问题?

//During the test the env variable is set to test
process.env.NODE_ENV = 'test';

let mongoose = require("mongoose");
let User = require('../models/User');

//Require the dev-dependencies
let chai = require('chai');
let chaiHttp = require('chai-http');
let app = require('../app');
let should = chai.should();

chai.use(chaiHttp);
//Our parent block
describe('Users', function () {
  beforeEach(function (done) { //Before each test we empty the database
    User.remove({}, function (err) { 
      done();         
    });     
  });
  /*
   * Test the /GET route
   */
  describe('/GET users', function () {
    it('it should GET all the users', function (done) {
      chai.request(app)
        .get('/users')
        .end(function (err, res) {
            res.should.have.status(200);
            res.body.should.be.a('array');
            res.body.length.should.be.eql(0);
          done();
        });
    });
  });

});

【问题讨论】:

  • 您确定您正确配置了与数据库的连接吗?当您致电User.remove 时,连接已打开?
  • remove 方法是什么?我在docs 中找不到remove 方法。所以你可能已经实现了它。我的猜测是 remove 方法永远不会调用回调函数,因此永远不会调用 done 并因此超时。 PS:如果您想删除数据库中的所有条目,可以使用truncate

标签: node.js express mocha.js chai


【解决方案1】:

假设您的连接工作正常并且它只是一个超时问题,您需要使用 this.timeout() 函数将超时时间延长到超出默认值(2000 毫秒)的时间。例如,在 beforeEach 函数中添加 this.timeout(10000) 会将超时设置为 10 秒,这将使您的 User.remove 调用有更多时间来完成。

这是这个 SO 答案中的一个示例:How to set timeout on before hook in mocha?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-30
    相关资源
    最近更新 更多