使用 Mocha 在回调返回的数组中循环
Loop in a callback returned array using Mocha
我正在努力实现这样的目标:
describe("TEST",function() {
Offer.find({},{_id:1, title:1}).exec(function(error, offers) {
for (var i = 0; i < offers.length; i++) {
it("Ask transaction : " + offers[i].title, function(done) {
// do something with offers[i];
}
}
...
但是 Mocha 甚至没有检测到文件中的测试。为什么?
每个测试用例都以 it("", function(){ /* write test code here */ } )
代码块开始。
如果您正在考虑执行一些测试设置,例如插入数据,那么您可以使用 before
函数来执行这些操作。
示例:
describe("TEST",function() {
before(function() {
// runs before all tests in this block
});
it("should blah", function(done) {
// Your test case starts here.
}
}
摩卡官网有例子可以参考;
所以,感谢您的回答和一些研究,我设法做到了我想要的。
describe("TRANSACTIONS TESTS",function() {
var offers;
before(function(done) {
Offer.find({},{_id:1, title:1}).exec(function(error, result) {
offers = result;
done();
});
});
it("TEST ALL OFFERS", function(done) {
for (var i = 0; i < offers.length; i++) {
const tmp_i = i;
server
.post('/transactions')
.send(data)
.expect("Content-type",/json/)
.expect(200)
.end(function(err,res) {
// DO TEST STUFF HERE
if (tmp_i == offers.length - 1) {
done();
}
});
}
});
const 变量是避免错误所必需的(i 始终等于数组的最大大小而不是递增)
我正在努力实现这样的目标:
describe("TEST",function() {
Offer.find({},{_id:1, title:1}).exec(function(error, offers) {
for (var i = 0; i < offers.length; i++) {
it("Ask transaction : " + offers[i].title, function(done) {
// do something with offers[i];
}
}
...
但是 Mocha 甚至没有检测到文件中的测试。为什么?
每个测试用例都以 it("", function(){ /* write test code here */ } )
代码块开始。
如果您正在考虑执行一些测试设置,例如插入数据,那么您可以使用 before
函数来执行这些操作。
示例:
describe("TEST",function() {
before(function() {
// runs before all tests in this block
});
it("should blah", function(done) {
// Your test case starts here.
}
}
摩卡官网有例子可以参考;
所以,感谢您的回答和一些研究,我设法做到了我想要的。
describe("TRANSACTIONS TESTS",function() {
var offers;
before(function(done) {
Offer.find({},{_id:1, title:1}).exec(function(error, result) {
offers = result;
done();
});
});
it("TEST ALL OFFERS", function(done) {
for (var i = 0; i < offers.length; i++) {
const tmp_i = i;
server
.post('/transactions')
.send(data)
.expect("Content-type",/json/)
.expect(200)
.end(function(err,res) {
// DO TEST STUFF HERE
if (tmp_i == offers.length - 1) {
done();
}
});
}
});
const 变量是避免错误所必需的(i 始终等于数组的最大大小而不是递增)