[英]Assert number of tests run by mocha.js
有没有办法断言 mocha 运行的测试数量?
例如:
afterAllTests(() => {
expect(mocha.numTestsRun).to.be.greaterThan(400);
});
我最近从mocha
7.1.2
升级到9.1.3
并且-R
速记参数停止工作。 我的测试套件从运行 ~400 个测试变成只运行 ~10 个顶级测试。 切换回--recursive
解决了这个问题,但我想确保不会再发生这样的事情。
我的package.json
看起来像这样:
{
"scripts": {
"integrationTest": "mocha --recursive spec test/integration",
}
}
与其计算到目前为止已经运行的测试数量,我会计算已经用 Mocha 声明的测试数量。 这确保无论执行顺序如何,对测试总数的检查都保持有效。
要计算测试总数,我们需要递归计算顶级套件及其所有子套件中声明的测试数量(没有捷径 AFAIK)。
我们首先声明一个新测试(它可以放在任何地方),其唯一目的是计算测试总数。
在这个测试中,我们可以使用this.runnable().parent
来获取包含套件。 反过来,套件还有一个属性parent
,可用于获取下一个更高的包含套件,一直到顶级套件(由 Mocha 隐式定义)。 顶级套件的属性root
设置为true
。
现在,与任何其他套件一样,顶级套件具有属性tests
和suites
,可用于分支所有后代套件并计算声明的测试总数。
it('total number of tests should be > 400', function() { // Use `function()`, don't use `() =>`...
let suite0 = this.runnable().parent; // ...because we need to access `this`.
while (!suite0.root) suite0 = suite0.parent;
// suite0 is now the top-level suite
// Recursiveliy count the number of tests in each suite
const countTests = (cnt, suite) => suite.suites.reduce(countTests, cnt + suite.tests.length);
const totalTests = countTests(0, suite0);
expect(totalTests).to.be.greaterThan(400);
});
这将计算所有测试,包括标记为skip
测试(但我想这就是您想要的)。
还要注意 - 显然 - 测试计数测试本身只有在您运行 Mocha 时不要忘记包含它时才有效。 将测试逻辑移动到钩子before
或after
的顶层不会有太大变化,因为这些钩子与在同一范围内声明的测试具有相同的可见性。 您可以将该测试放在spec
文件夹内的文件中,因此即使没有--recursive
标志也会执行它。 作为最后的手段,您可以在环境变量中设置测试数量并在 Mocha 之外检查该值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.