如何:
describe("My describe", function() {
let a;
it("test1", function() {
a = [1, 2, 3];
});
a.forEach(function(i) {
it("test" + i, function() {
console.log(i);
});
});
});
如果你的测试是异步的,你需要将done
回调添加到他们。但是对于使用console.log()
这个简单的例子,这是没有必要的。
- 编辑 -
我认为答案是“不,你不能这样做”。我加了一些console.log
报表,看看发生了什么事:
describe("My describe", function() {
let a = [1, 2];
it("First test", function() {
console.log('First test');
a = [1, 2, 3];
});
a.forEach(function(i) {
console.log(`forEach ${i}`);
it("Dynamic test " + i, function() {
console.log(`Dynamic test ${i}`);
});
});
});
这是输出:
$ mocha
forEach 1
forEach 2
My describe
First test
✓ First test
Dynamic test 1
✓ Dynamic test 1
Dynamic test 2
✓ Dynamic test 2
3 passing (7ms)
所以,mocha
运行整个describe
块和运行任何之前创建的动态测试it
块。在测试开始后,我看不出如何从it
块内部生成更多动态测试。
您的数组创建必须位于it
块内吗?
你想它()在它访问的变量超出范围 – Fahadsk