MongoDB连接期间的Mocha超时

时间:2018-05-12 07:01:35

标签: javascript node.js mongodb mocha chai

Mongo新手在这里。我正在尝试使用Mocha,Chai连接单元测试我的mongo db集合。但每次我运行测试时,连接似乎都会超时。我已将timeout中的mocha.opts增加到50K ms,但连接似乎仍然超时。我无法理解为什么?

这是我的代码

use strict';
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const chai = require('chai');
const expect = chai.expect;



/**
 * 
 * Create a new schema that accepts a firstname and lastname and employee id
 */

 const testSchema = new Schema({
     firstname : {type: String,required:true},
     lastname : {type: String, required:true},
     id : {type : Number, required : true}
 });

 /**
  * 
  * Create a new collection name employee_details 
  */

  const employee_details = mongoose.model('employee_details',testSchema);

  describe('Create a connection with the database',()=>{
      before((done)=>{
          mongoose.connect('mongodb://127.0.0.1:27017/new_demo');
   //I tried changing the url to mongodb://localhost/new_demo but it didn't work
          const db  = mongoose.connection;
          db.on('error',console.error.bind(console,'Error connecting to DB'));
          db.once('open',()=>{
              console.log('Connected to new_demo db');
              done();
          });
      });

  });


  describe('Test Database function',()=>{
      //Save something with value Mike Stevens, 19981
      it('saves a new record',(done)=>{
        var first_record = employee_details({
            firstname : 'Mike',
            lastname : 'Stevens',
            id : 19981
        });

        first_record.save(done);
      });



      after((done)=>{
          mongoose.connection.db.dropDatabase(()=>{
              mongoose.connection.close(done);
          });
      });
  });

到目前为止我尝试过的事情

  • 增加了mocha的超时
  • 将连接网址更改为mongodb://localhost/new_demomongodb://localhost:27017/new_demo
  • 在shell中启动mongod,然后尝试运行mocha测试

错误消息是

Error: Timeout of 50000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/ab/ab/abcd/api-testing/mongo-testing/my-mongo-tests/test/create_connection.js)

根据错误消息,应调用done,这在代码中完成。那为什么会出现这个错误?

编辑1:完整错误消息

Test Database function
    1) saves a new record
    2) "after all" hook


  0 passing (50s)
  2 failing

  1) Test Database function
       saves a new record:
     Error: Timeout of 50000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/ab/ab/abcd/api-testing/mongo-testing/my-mongo-tests/test/create_connection.js)


  2) Test Database function
       "after all" hook:
     TypeError: Cannot read property 'dropDatabase' of undefined
      at Context.after (test/create_connection.js:56:34)

2 个答案:

答案 0 :(得分:0)

我应该更加小心错误消息和堆栈跟踪。这是实际的堆栈跟踪(现在也发布了问题)

  Test Database function
    1) saves a new record
    2) "after all" hook


  0 passing (50s)
  2 failing

  1) Test Database function
       saves a new record:
     Error: Timeout of 50000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/ab/ab/abcd/api-testing/mongo-testing/my-mongo-tests/test/create_connection.js)


  2) Test Database function
       "after all" hook:
     TypeError: Cannot read property 'dropDatabase' of undefined
      at Context.after (test/create_connection.js:56:34)

第一个describe块不会打印任何内容。我删除了before块,其中连接正在describe块中完成并再次运行测试,我可以看到测试成功运行。

使用RoboMongo验证结果,并正确显示新数据库,并正确显示集合和记录。

答案 1 :(得分:0)

mocha测试用例与普通JS代码没有什么不同,因此它将遵循JS代码的范围隔离和流程。我试图修复测试用例以允许在各种测试用例和钩子之前/之后进行变量访问。

请注意,我没有执行实际测试用例,您可能需要修改以下代码才能使其成功运行

'use strict';
 const mongoose = require('mongoose');
 const Schema = mongoose.Schema;
 const chai = require('chai');
 const expect = chai.expect;



 /**
  * 
  * Create a new schema that accepts a firstname and lastname and employee id
  */
 const testSchema = new Schema({
     firstname: { type: String, required: true },
     lastname: { type: String, required: true },
     id: { type: Number, required: true }
 });

 /**
  * 
  * Create a new collection name employee_details 
  */
 const employee_details = mongoose.model('employee_details', testSchema);

 /**
  * Decalre the db const in this(global) context so this variable is visible by all test cases
  */
 const db;

 //  describe('Create a connection with the database', () => {
 //      // Seems redundet to something
 //      // Also the context is lost if you do this .. 
 //      // Thus not allowing for you to use variables .. const db in this case
 //      // If you still want this describe, you will have to use it like any other javascript function ... to expose the variables
 //  });


 describe('Test Database function', () => {

     // connect to database     
     before((done) => {
         mongoose.connect('mongodb://127.0.0.1:27017/new_demo');
         //Keep the url same which you use to debug you local application
         db = mongoose.connection;
         db.on('error', console.error.bind(console, 'Error connecting to DB'));
         db.once('open', () => {
             console.log('Connected to new_demo db');
             done();
         });
     });

     //Save something with value Mike Stevens, 19981
     it('saves a new record', (done) => {
         // Also if you want to increase the deafult timeout of a teast case
         // you will have to change the => to function(), because of the way 'this' context behaves
         // Thus : 
         //   it('saves a new record', function(done) {
         //      this.timeout(10000);
         //      .. test case code
         //   }
         var first_record = employee_details({
             firstname: 'Mike',
             lastname: 'Stevens',
             id: 19981
         });

         first_record.save(function(err) {
             if (err) return handleError(err);
             // saved!
             done();
             //I used a simple callback function instead, makes life easier and code understable
         })
     });



     after((done) => {
         mongoose.connection.db.dropDatabase(() => {
             mongoose.connection.close(done);
             // I am guessing same goes here .. 
             // keep it simple !!
         });
     });
 });

现在有些理论,理想情况是推荐或者更确切地说不在单元测试用例的范围内实际连接到数据库和/或修改外部实体的状态以任何方式(因为您特别提到它是一个单元测试用例')。

单元测试应该避免进行外部调用或调用实际的API。我们应该存根调用,并且在我们的测试用例中断言调用是在我们预期的时候进行的,或者是在提供了适当的输入时。

以下是谈话的一个例子:

//This is myGLobalServiceLoactor which is used in actual code which is to be tested.
 myGLobalServiceLoactor = {
     database: {
         save: sinon.stub(),
         find: sinon.stub()
     }
 }

 it('to check if external method is called ', () => {
     let person_to_Save = {
         //. . . 
         //. . . 
     }
     proxyPersonInterface.savePerson(input_person).then((status) => {
         // check if our stubbeb function is called
         assert(myGLobalServiceLoactor.database.save.calledOnce);
     });

 });

您可以使用辅助库(如Sinonrewire来存储和代理单元测试用例中的实际模块。    希望有所帮助。