蒙古语访问摩卡testing

所以我想在一些unit testing之后清理我的db(之前或之后)。

基本上,你将在我的代码块中看到的代码位于摩卡的afterAll块中。 我正在使用webdriver.io testrunner运行我的testing。

我不明白的是,如何从连接范围之外使用db的东西,请参阅:

 function createConnection(){ MongoClient.connect('mongodb://127.0.0.1:24001/meteor', function(err, db) { if (err) throw err; console.log("connected to the mongoDB !"); let myCollection = db.collection('test_collection'); // do stuff with myCollection }); } 

如果可能的话,我宁愿像这样:

 function createConnection(){ MongoClient.connect('mongodb://127.0.0.1:24001/meteor', function(err, db){ if (err) throw err; } } function getCollection(name){ return db.collection(name) //don't have db at this scope, problem? } //app.js createConnection(); let myCollection = getCollection('data'); ...//do stuff with myCollection closeConnection(); 

这可能吗?

如果你想以你描述的方式连接到一个MongoDB数据库,你可以使用JavaScript的承诺,以确保你调用getCollection时定义了db 。 你将包含在你的afterAll块中的代码将如下所示:

 function createConnection(connection) { // return a promise return new Promise((resolve, reject) => { MongoClient.connect('mongodb://127.0.0.1:24001/meteor', function (err, db) { if (err) { // rejects with error if connection fails reject(err); } // returns handle to database if connection successful resolve(db); }); }); } // function takes handle to database and collection name function getCollection(db, name) { return db.collection(name); } // test it works createConnection().then((db) => { let myCollection = getCollection(db, 'foo'); // do stuff with one collection // eg myCollection.deleteOne({ foo: 1 }); // ... // do stuff with another collection myCollection = getCollection(db, 'bar'); // eg myCollection.insert({ bar: 1 }); // ... // ensure you catch any errors and log them to the console }).catch(console.error); 

请注意,我习惯了一点ES6语法,但是它和ES5完全一样。

经验法则是,你总是在你的testing用例中嘲笑诸如数据库或http请求之类的东西。 看看类似mongo-mock的东西,然后用它来代替。