2015-04-28 56 views
1

我想做一个吞咽任务,用一条命令运行我所有的mocha测试。 (我的测试需要连接与猫鼬到DB)如何创建猫鼬连接测试时使用gulp摩卡

然后我得到这个错误: { [Error: Trying to open unclosed connection.] state: 1 }

经过一番研究,我发现这个职位: Mongoose Trying to open unclosed connection

它说我应该使用createConnection()代替'connect()`。

这是现在的问题:

我怎么能使用beforeafter的测试,我怎么能叫后DB done连接遍历每个测试用例之前?

+0

是否运行在'mongoose.connect()'命令不止一次,甚至跨多个测试脚本?你应该只需要一次执行'connect'命令。 –

+0

是的,我在每个测试规范中运行它们。我这样做的原因是我想让我可以单独运行每个测试规范,而我可以一次运行所有测试规范。如果我只运行一次运行'mongoose.connect()',我想我需要处理一些吞噬脚本来使这成为可能。 – Yushi

回答

0

以下是我一饮而尽任务:

gulp.task('mocha', function() { 
    var testFile = argv['f']; 
    var fullPaths; 
    if (testFile) { 
    fullPaths = paths.server + 'tests/' + testFile; 
    } else { 
    fullPaths = serverUnitTestFiles; 
    } 
    var dbConnectionModulePath = paths.server + 'tests/db-connection.js'; 
    var dbConnection = gulp.src(dbConnectionModulePath, { read: false }); 
    var tests = gulp.src(fullPaths, { read: false }); 
    return series(dbConnection, tests) 
     .pipe(mocha({ reporter: 'nyan' })); 
}); 

这里是DB-connection.js模块:

'use strict'; 

var mongoose = require('mongoose'), 
    connection = mongoose.connection, 
    dbName = 'learnMongo'; 

before(function (done) { 
    connection.on('error', console.error); 
    connection.once('open', function() { 
    done(); 
    }); 
    mongoose.connect('mongodb://localhost:27017/' + dbName); 
}); 

after(function (done) { 
    connection.close(done); 
});