mocha-list-tests 包很有用,但仅适用于 BDD 样式 describe() 和 it(),如果您 .skip() 进行任何测试,它会中断,因为它会模拟 it()。
如果您需要克服其中任何一个问题或获取有关测试的其他信息,您可以自己执行此操作的一种方法是利用 Mocha 的根 before() 钩子。这将在 Mocha 加载所有文件之后但在执行任何测试之前执行,因此您需要的所有信息都存在于那个时候。
这样,很容易在--list-only 命令行选项中打补丁来切换测试运行的行为,而无需添加或更改任何其他内容。
关键是before()钩子中的this是Mocha的Context,其中的.test指的是钩子本身。所以this.test.parent 指的是根套件。从那里,您可以沿着 .suites 数组树和每个套件的 .tests 数组树向下走。
收集到你想要的任何东西后,你必须输出它并退出该过程以阻止 Mocha 继续。
纯文本示例
鉴于 root.js:
#!/bin/env mocha
before(function() {
if(process.argv.includes('--list-only')) {
inspectSuite(this.test.parent, 0);
process.exit(0);
}
// else let Mocha carry on as normal...
});
function inspectSuite(suite, depth) {
console.log(indent(`Suite ${suite.title || '(root)'}`, depth));
suite.suites.forEach(suite => inspectSuite(suite, depth +1));
suite.tests.forEach(test => inspectTest(test, depth +1));
}
function inspectTest(test, depth) {
console.log(indent(`Test ${test.title}`, depth));
}
function indent(text, by) {
return ' '.repeat(by) + text;
}
还有test.js:
#!/bin/env mocha
describe('foo', function() {
describe('bar', function() {
it('should do something', function() {
// ...
});
});
describe('baz', function() {
it.skip('should do something else', function() {
// ...
});
it('should do another thing', function() {
// ...
});
});
});
然后像往常一样运行mocha 会得到你期望的测试结果:
foo
bar
✓ should do something
baz
- should do something else
✓ should do another thing
2 passing (8ms)
1 pending
但是运行 mocha --list-only 会给你(不运行任何测试):
Suite (root)
Suite foo
Suite bar
Test should do something
Suite baz
Test should do something else
Test should do another thing
JSON 示例
root.js
#!/bin/env mocha
before(function() {
let suites = 0;
let tests = 0;
let pending = 0;
let root = mapSuite(this.test.parent);
process.stdout.write(JSON.stringify({suites, tests, pending, root}, null, ' '));
process.exit(0);
function mapSuite(suite) {
suites += +!suite.root;
return {
title: suite.root ? '(root)' : suite.title,
suites: suite.suites.map(mapSuite),
tests: suite.tests.map(mapTest)
};
}
function mapTest(test) {
++tests;
pending += +test.pending;
return {
title: test.title,
pending: test.pending
};
}
});
使用与以前相同的测试脚本会给你:
{
"suites": 3,
"tests": 3,
"pending": 1,
"root": {
"title": "(root)",
"suites": [
{
"title": "foo",
"suites": [
{
"title": "bar",
"suites": [],
"tests": [
{
"title": "should do something",
"pending": false
}
]
},
{
"title": "baz",
"suites": [],
"tests": [
{
"title": "should do something else",
"pending": true
},
{
"title": "should do another thing",
"pending": false
}
]
}
],
"tests": []
}
],
"tests": []
}
}