为摩卡testing设置数据库连接的最佳实践和最有效的方法
我有一套testing,我在我的代码上运行。 在testing运行之前,我想打开一个到testing数据库的数据库连接,并确保数据库是空的。 这个连接将保持对所有testing打开。 然后,当所有testing完成后,closures数据库连接并清空数据库。
我目前的解决scheme涉及打开每个文件的连接,这将导致大量的连接整体。 这将是理想的打开连接一次 – >运行testing – >清除数据库 – >closures连接一次。
这是我的一个摩卡testing文件的代码:
import {assert} from 'chai'; import mongoose from 'mongoose'; import User from '../../../server/models/user.js'; import 'dotenv/config'; mongoose.connect(process.env.DB_TEST).then(db => { describe('User Model', function() { it('Save', function(done) { var john = new User({ name: { first: 'John', last: 'smith' }, email: 'john.smith@gmail.com', type: 'student' }); john.save(done); }); }); }).catch(err => { console.log('Failed to connect to testing database: ' + err); });
目前,这个代码是完全function的。 不过,我确信有更好的方法来处理打开,清除和closures我的testing集合的数据库连接。
你可以使用我所说的Root level hooks
。
例如:
testing文件
test0.es6 test1.es6 test2.es6 ...
使用test0.es6
文件来处理数据库连接,如:
// ROOT HOOK Executed before the test run before((done) => { connectToDatabase() .then(() => { ... done(); }) .catch(...); }); // ROOT HOOK Excuted after every tests finished after((done) => { disconnectFromDatabase() .then(() => { ... done(); }) .catch(...); });
使用其他文件来使用数据库连接执行testing:
/** @test {core} */ describe('core', () => { /** @test {core#executeCommandApi} */ describe('executeCommandApi()', () => { it(...); }); });
注意事项: 摩卡以字母顺序呼叫您的文件
- 在多个文件中分割摩卡APItesting
- 你怎么能用superagent来使用cookies?
- 使用mocha-phantomjs来自动化functiontesting
- Zombie.js pressButton长callback延迟
- 使用mocha.jstestingjQyery.get不起作用,其他延迟(RSVP)
- 如何在Mochatesting用例中使用setTimeout()函数?
- 有没有更好的方式在摩卡书写testing语句?
- 摩卡如何公开一个节点控制器函数来testing脚本
- 使用Gulp,Mocha,Browserify进行正确configuration,以执行服务器端testing的客户端testing