How to skip to next next describe on error in Moch

2019-07-13 22:54发布

I have a bunch of describes that test different parts of an API. In one section, all the tests are dependent on one test succeeding. I want to make Mocha run the first test, and if it fails, skip all following tests and run the next test suite for the next section of the API.

mocha --bail would stop testing altogether after the first fail, and won't continue to the next section.

mocha-steps is a viable solution, but I prefer not to use any external libraries. In addition, it doesn't skip steps after the failure, it doesn't print them altogether. Like I said, it's a viable solution, but not ideal.

What would be the best way to implement this behavior in vanilla Mocha?

2条回答
等我变得足够好
2楼-- · 2019-07-13 23:47

Although I up-voted the accepted answer, I wasn't able to get a Mocha it test to run inside a before function. Instead I had to separate the first test into its own describe and set a variable if the test passed, then check the variable in the before of the describe containing all the other tests.

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', ...)
});
查看更多
女痞
3楼-- · 2019-07-13 23:48

Put what you call your "first test" in a before hook inside a describe block that contains all the other tests:

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

    it("test 1", function () { ... });
    it("test 2", function () { ... });
    // ...
});

This is the proper way in "vanilla Mocha" to set a dependency between the code in the before hook and each of the tests. If the before hook fails, Mocha will report it, and it will skip all the tests in the describe block. If you have other tests elsewhere, they will still run.

查看更多
登录 后发表回答