我正在尝试使用 Mocha 测试异步 JavaScript,但在循环异步填充数组时遇到一些问题。
我的目标是创建 N (=arr.length
) 测试,数组的每个元素一个。
可能我缺少一些关于摩卡语义的东西。
到目前为止,这是我的(非工作的)简化代码:
var arr = []
describe("Array test", function(){
before(function(done){
setTimeout(function(){
for(var i = 0; i < 5; i++){
arr.push(Math.floor(Math.random() * 10))
}
done();
}, 1000);
});
it('Testing elements', function(){
async.each(arr, function(el, cb){
it("testing" + el, function(done){
expect(el).to.be.a('number');
done()
})
cb()
})
})
});
我收到的输出是:
Array test
✓ Testing elements
1 passing (1s)
我想要一个像这样的输出:
Array test
Testing elements
✓ testing3
✓ testing5
✓ testing7
✓ testing3
✓ testing1
5 passing (1s)
关于如何写这个有任何帮助吗?
我让这个工作的唯一方法有点混乱(因为它需要一个虚拟测试;原因是你不能直接嵌套一个it()
在另一个里面it()
,它要求“父母”是describe()
,你需要一个it()
因为describe()
不支持异步):
var expect = require('chai').expect;
var arr = [];
describe('Array test', function() {
before(function(done){
setTimeout(function(){
for (var i = 0; i < 5; i++){
arr.push(Math.floor(Math.random() * 10));
}
done();
}, 1000);
});
it('dummy', function(done) {
describe('Testing elements', function() {
arr.forEach(function(el) {
it('testing' + el, function(done) {
expect(el).to.be.a('number');
done();
});
});
});
done();
});
});
The dummy
will最终出现在你的输出中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)