【发布时间】:2018-05-12 07:01:35
【问题描述】:
这里是Mongo新手。我正在尝试使用 Mocha、Chai 连接一个单元测试我的 mongo db 集合。但是每次我运行测试时,连接似乎都会超时。我已将mocha.opts 中的timeout 增加到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 的超时时间
- 将连接 URL 更改为
mongodb://localhost/new_demo和mongodb://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)
【问题讨论】:
-
那么你实际上是在shell中运行
mongod进程吗?究竟有哪些选择?单元测试实际在哪里运行?在同一台机器上还是这些可能在不同的虚拟机或类似的东西上? -
我只是在终端中运行
mongod,没有任何选项。单元测试在同一台机器上的不同终端中运行。 -
你不能没有选项运行,因为它在大多数情况下将无法启动。除非您创建了一个默认的数据目录名称,否则这实际上是不明智的。这是在哪个操作系统上?您至少可以从另一个终端窗口运行
mongoshell 吗?想想不止一个句子作为回应,准确地展示你在做什么,并“在你自己的问题中”回答所有这些问题。问题中的详细信息而不是 cmets。
标签: javascript node.js mongodb mocha.js chai