我想使用 mocha 将功能逐个功能、逐个测试地添加到我的程序中。
var assert = require('assert');
var mongoskin = require('mongoskin');
describe('basic database tests', function(){
before(function(){
});
it('should have 3 users', function(done){
var db = mongoskin.db('mongodb://localhost:27017/stuffTest', {safe:true});
db.collection('users').find().toArray(function (err,result){
console.log(result.length);
assert.equal(result.length,3);
});
});
});
这不起作用。无论我将内容放入测试中的哪个位置,我都会收到错误。通过这种安排,我收到错误:超时超过 2000 毫秒
这是设置数据库的代码。我以前的开发方式是用 console.logs 之类的东西乱扔我的代码。此代码使用 console.logs 让我知道集合是否为空,如果是,则它是否填充了 3 条记录。
var mongoskin = require('mongoskin')
var db = mongoskin.db('mongodb://localhost:27017/stuffTest', {safe:true})
db.collection('users').find().toArray(function (err,result){
console.log(result.length)
})
db.collection('users', {strict:true}, function(err, collection) {
if (err) {
console.log("The 'users' collection doesn't exist. Creating it with sample data...");
populateDB(users);
}
});
var populateDB = function(huh) {
console.log("Populating database...");
var name= huh.name;
var coll= huh.items;
db.collection(name, function(err, collection) {
collection.insert(coll, {safe:true}, function(err, result) {
console.log(result.length);
});
});
};
var users = [];
users.name = 'users';
users.items= [
{name: 'tim', email: '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8fe2ece4eae1e1eea1fbe6e2cfe8e2eee6e3a1ece0e2" rel="noreferrer noopener nofollow">[email protected]</a>', lists:[]},
{name: 'peri', email: '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d2a2b7a0bbbfb1b9b7bcbcb392b5bfb3bbbefcb1bdbf" rel="noreferrer noopener nofollow">[email protected]</a>', lists:[]},
{name: 'tim2', email: '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4b2628203f14213b0b322a23242465282426" rel="noreferrer noopener nofollow">[email protected]</a>', lists:[]}
];
我该如何编写这个测试?此代码加上 package.json 和 dropDb.js 位于:https://github.com/mckennatim/tdd
最佳答案
您没有调用完成
。如果您不在异步测试中调用 done
,您肯定会超时。修改测试以在回调结束时调用 done
。像这样:
it('should have 3 users', function(done){
var db = mongoskin.db('mongodb://localhost:27017/stuffTest', {safe:true});
db.collection('users').find().toArray(function (err,result){
console.log(result.length);
assert.equal(result.length,3);
done();
});
});
关于node.js - 关于使用 Node 和 mongo 迁移到 TDD,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22336543/