如何跳到下一个下一个描述摩卡中的错误

How to skip to next next describe on error in Mocha?

本文关键字:下一个 错误 摩卡 描述 何跳      更新时间:2023-09-26

我有一堆describe来测试API的不同部分。在一个部分中,所有测试都依赖于一个测试成功。我想让 Mocha 运行第一个测试,如果失败,请跳过所有后续测试并为 API 的下一部分运行下一个测试套件。

mocha --bail将在第一次失败后完全停止测试,并且不会继续下一部分。

mocha-steps是一个可行的解决方案,但我不喜欢使用任何外部库。此外,它不会在失败后skip步骤,也不会完全打印它们。就像我说的,这是一个可行的解决方案,但并不理想。

在香草摩卡中实现此行为的最佳方法是什么?

将你所谓的"第一个测试"放在一个包含所有其他测试的describe块内的before钩中:

describe("bunch of related tests", function () {
    before(function () {
        // "first test" here
    });
    it("test 1", function () { ... });
    it("test 2", function () { ... });
    // ...
});

这是"vanilla Mocha"中设置before钩子中的代码与每个测试之间的依赖关系的正确方法。如果before钩失败,Mocha 会报告它,它会跳过describe块中的所有测试。如果您在其他地方有其他测试,它们仍将运行。

虽然我对接受的答案投了赞成票,但我无法让 Mocha it 测试在 before 函数中运行。相反,我必须将第一个测试分成它自己的describe,如果测试通过,则设置一个变量,然后在包含所有其他测试的describe before中检查变量。

let passed = false
describe('first test', function() {
  it('run the first test', function(done) {
    if (theTestPassed)
      passed = true
    done()
  })
})
describe('rest of the tests', function() {
  before(function() {
    if (!passed)
      throw new Error('skip rest of the tests')
  });
  it('second test', ...)
  it('third test', ...)
});