【问题标题】:How to skip to next next describe on error in Mocha?如何跳到下一个关于 Mocha 错误的描述?
【发布时间】:2016-05-25 06:42:29
【问题描述】:

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

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

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

在 vanilla Mocha 中实现此行为的最佳方法是什么?

【问题讨论】:

    标签: javascript mocha.js


    【解决方案1】:

    将您所谓的“第一个测试”放在包含所有其他测试的 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 块中的所有测试。如果您在其他地方有其他测试,它们仍会运行。

    【讨论】:

      【解决方案2】:

      尽管我对接受的答案投了赞成票,但我无法让 Mocha it 测试在 before 函数中运行。相反,我不得不将第一个测试分成自己的describe,并在测试通过时设置一个变量,然后检查包含所有其他测试的describebefore 中的变量。

      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', ...)
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-23
        • 1970-01-01
        相关资源
        最近更新 更多