【发布时间】:2015-07-23 11:52:53
【问题描述】:
我正在尝试异步从配置文件在运行测试套件之前动态加载设置。 测试套件需要获取一个配置对象进行测试,并从中创建一个服务器连接 beforeEach 测试 - 然后关闭服务器连接 afterEach 测试。 我有以下代码大纲,但测试套件(嵌套 describe)总是在设置(before)函数完成之前调用;这意味着 testConfigs 数组始终为空。 我正在尝试做的事情是可以实现的,还是我必须从根本上改变测试?
describe('test server configs', function ()
{
var testConfigs = [];
before('get server configurations', function (done) {
var conf = path.resolve('conf');
fs.readdir(conf, function (err, files) {
files.forEach(function (file) {
var config = require(path.join(conf, file));
testConfigs.push(config);
});
}
console.dir(testConfigs); //prints the non-empty array
done(err);
});
});
describe('server test suite', function () {
if (testConfigs.length == 0) {
it('No server configurations to test!'); //0 tests passed, 1 pending
}
else {
testConfigs.forEach(function (config) { //testConfigs is empty here
var connection;
beforeEach('connect to the server', function (done) {
connection = ServerConnection(config);
done();
});
it('should do something with the remote server', function (done) {
//test something with the 'connection' object
expect(connection.doSomething).withArgs('just a test', done).not.to.throwError();
});
afterEach('close connection', function (done) {
connection.close(done);
});
});
}
});
});
结果:
test server configs
[ [ 'local-config.json',
{ host: 'localhost',
user: 'username',
pass: 'password',
path: '/' } ],
[ 'foo.com-config.json',
{ host: 'foo.com',
user: 'foo',
pass: 'bar',
path: '/boo/far' } ] ]
server test suite
- No server configurations to test!
0 passing (25ms)
1 pending
【问题讨论】:
-
作为快速修复,您可以使用
fs.readdirSync()(我认为异步方式不可能,但我自己没有调查过)。 -
呃!我希望有一些比不得不诉诸同步操作更优雅的东西。在这种情况下应该没问题,但是当没有同步函数可用时怎么办!?我的意思是不是 before[Each]/after[Each] 实用程序中的重点
标签: javascript asynchronous mocha.js bdd