Mocha JS:如何在description /it测试函数中引用asynch before函数的成员
Mocha JS: How to reference members from asynch before function in describe/it test functions
我试图动态加载设置异步从配置文件之前运行测试套件。测试套件需要接受一个配置对象进行测试,并在每个测试前从它创建一个服务器连接-然后在每个测试后关闭服务器连接。我有下面的代码大纲,但是测试套件(嵌套的描述)总是在设置(之前的)函数完成之前调用;这意味着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需要你的测试的那一刻。
相关文章:
- 如何在JavaScript中将字符串转换为函数引用
- IIFE中的函数引用不可用
- Wordpress中的Javascript出现匿名函数/引用错误
- 将函数引用存储在散列中在javascript中无法正常工作
- Google可视化addListener调用函数引用错误
- 如何存储包含参数的JS函数引用
- 如何从函数引用元素(从事件侦听器调用)
- 将函数引用传递给嵌套闭包
- Javascript递归函数引用了这一点
- 在Node.js中,从同一文件中的另一个函数引用一个函数会导致'ReferenceError:-函数-未定义
- 为什么将函数引用封装到匿名函数中可以更正'这'指向
- 如何在ES6中使用Arrow函数引用对象内部的其他函数
- 复制不带属性的函数引用
- 在控制器中使用具有函数引用的服务
- Jquery 和闭包或函数引用不起作用
- 将函数引用传递给函数失败
- Jasmine spyOn:当传递间谍函数引用时如何使其工作
- 从 Javascript 中的嵌套函数引用对象成员
- Typescript-不同文件中的模块函数引用-“;找不到符号“;
- 与许多事件侦听器和函数引用一个对象相比,什么是更好的方法