在 mocha 中循环()
Looping in mocha over it()
我想用 mocha 迭代几组测试文件,但我的 it() 从未执行过。
var unitTests = JSON.parse(fs.readFileSync('./test/unitTests.json', 'utf8'));
for (test in unitTests.unitTests) {
var inputFilename = unitTests.unitTests[test].input;
console.log(inputFilename);
it('do stuff with the file', function(done) {
...
});
}
我的 console.log 语句确实打印了每个输入文件名,但 it() 中的代码永远不会执行。如果我注释掉循环,它 运行 就好了。
看来我的假设不正确...
我如何查看 mocha 中的 it()?
原来我原来的问题是错的
我在调试器中 运行 执行此操作,我看到 console.log 语句在 it() 块执行之前执行。然后我退出了程序。如果我让它 运行 我的 it() 会按预期阻塞 运行。
看起来 it() 的异步特性让我很困惑。
始终将测试包装在 describe
块中:
const fs = require('fs');
var unitTests = JSON.parse(fs.readFileSync('./test/unitTests.json', 'utf8'));
function doStuff(test) {console.log("did stuff with " + test.input)}
describe('runTests', function() {
unitTests.unitTests.forEach(function(test) {
it('does stuff with ' + test.input, function(done) {
var res = doStuff.apply(null, [test]);
done();
});
});
});
./node_modules/.bin/mocha test.js
的输出
runTests
did stuff with 1.foo
✓ does stuff with 1.foo
did stuff with 4.foo
✓ does stuff with 4.foo
did stuff with 3.foo
✓ does stuff with 3.foo
did stuff with 2.foo
✓ does stuff with 2.foo
4 passing (8ms)
更多信息:https://mochajs.org/#dynamically-generating-tests
ps。我用
播种我的 unitTests.json
{"unitTests": [{"input": "1.foo"},{"input": "4.foo"},{"input": "3.foo"},{"input": "2.foo"}]}
我想用 mocha 迭代几组测试文件,但我的 it() 从未执行过。
var unitTests = JSON.parse(fs.readFileSync('./test/unitTests.json', 'utf8'));
for (test in unitTests.unitTests) {
var inputFilename = unitTests.unitTests[test].input;
console.log(inputFilename);
it('do stuff with the file', function(done) {
...
});
}
我的 console.log 语句确实打印了每个输入文件名,但 it() 中的代码永远不会执行。如果我注释掉循环,它 运行 就好了。
看来我的假设不正确...
我如何查看 mocha 中的 it()?
原来我原来的问题是错的
我在调试器中 运行 执行此操作,我看到 console.log 语句在 it() 块执行之前执行。然后我退出了程序。如果我让它 运行 我的 it() 会按预期阻塞 运行。
看起来 it() 的异步特性让我很困惑。
始终将测试包装在 describe
块中:
const fs = require('fs');
var unitTests = JSON.parse(fs.readFileSync('./test/unitTests.json', 'utf8'));
function doStuff(test) {console.log("did stuff with " + test.input)}
describe('runTests', function() {
unitTests.unitTests.forEach(function(test) {
it('does stuff with ' + test.input, function(done) {
var res = doStuff.apply(null, [test]);
done();
});
});
});
./node_modules/.bin/mocha test.js
runTests
did stuff with 1.foo
✓ does stuff with 1.foo
did stuff with 4.foo
✓ does stuff with 4.foo
did stuff with 3.foo
✓ does stuff with 3.foo
did stuff with 2.foo
✓ does stuff with 2.foo
4 passing (8ms)
更多信息:https://mochajs.org/#dynamically-generating-tests
ps。我用
播种我的unitTests.json
{"unitTests": [{"input": "1.foo"},{"input": "4.foo"},{"input": "3.foo"},{"input": "2.foo"}]}