我试图动态加载设置异步从配置文件之前运行测试套件。测试套件需要接受一个配置对象进行测试,并在每个测试前从它创建一个服务器连接-然后在每个测试后关闭服务器连接。我有下面的代码大纲,但是测试套件(嵌套的描述)总是在设置(之前的)函数完成之前调用;这意味着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
可以在测试运行已经开始时添加新的测试。如果您想要动态地生成测试用例,那么您应该在测试开始之前进行。可以使用同步方法在测试前读取配置
var testConfigs = []
var conf = path.resolve('conf');
var files = fs.readdirSync(conf);
files.forEach(function (file) {
var config = require(path.join(conf, file));
testConfigs.push(config);
});
describe('server test suite', function () {
testConfigs.forEach(function (config) {
//describe your dynamic test cases
});
});
乌利希期刊指南26.07.15
如果你因为某些原因不能使用同步功能,你可以在设置完成后以编程方式运行mocha。
var Mocha = require('mocha');
var fs = require('fs');
var mocha = new Mocha({});
var testConfigs = global.testConfigs;
fs.readdir(conf, function (err, files) {
files.forEach(function (file) {
var config = require(path.join(conf, file));
testConfigs.push(config);
});
mocha.run();
});
你必须通过全局作用域传递testConfigs
,因为mocha同步加载带有test的模块,这个配置必须准备好,直到mocha需要你的测试的那一刻。