如何:
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