Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocha.js: to run "after" hook even if test suit fails

Is it possible to run "after" hook even if one of tests (suite) fails?

like image 676
WHITECOLOR Avatar asked May 25 '13 07:05

WHITECOLOR


People also ask

Do mocha tests run sequentially?

Mocha tests run serially, allowing for flexible and accurate reporting, while mapping uncaught exceptions to the correct test cases.

Does Mocha run tests in parallel?

Mocha does not run individual tests in parallel. That means if you hand Mocha a single, lonely test file, it will spawn a single worker process, and that worker process will run the file. If you only have one test file, you'll be penalized for using parallel mode. Don't do that.

How do you skip the mocha test?

Mocha has a feature that allows you to skip tests by appending . skip to a test-suite or a test-case, or by prepending it with an x (e.g., xdescribe(...) instead of describe(...) ).


1 Answers

Yes, both after and afterEach hooks should be run when a test fails.

See these github issues for related discussions and changes: #94, #125, #143, #690.

Here is an example to prove my claim:

describe('test', function() {
  after(function() { console.log('after'); });
  afterEach(function() { console.log('afterEach'); });

  it('fails sync', function(done) {
    after(function() { console.log('inner after 1'); });
    throw new Error('failed');
  });

  it('fails async', function(done) {
    after(function() { console.log('inner after 2'); });
    process.nextTick(function() {
      throw new Error('failed');
    });
  });
});

which produces the following output with mocha 1.1.12:

  ․afterEach
․afterEach
after
inner after 1
inner after 2


  0 passing (5 ms)
  2 failing

1) test fails sync:
 Error: failed
  at Context.<anonymous> (/private/tmp/so/test/main.js:7:11)
  at Test.Runnable.run (/private/tmp/so/node_modules/mocha/lib/runnable.js:194:15)
  at Runner.runTest (/private/tmp/so/node_modules/mocha/lib/runner.js:355:10)
  at /private/tmp/so/node_modules/mocha/lib/runner.js:401:12
  at next (/private/tmp/so/node_modules/mocha/lib/runner.js:281:14)
  at /private/tmp/so/node_modules/mocha/lib/runner.js:290:7
  at next (/private/tmp/so/node_modules/mocha/lib/runner.js:234:23)
  at Object._onImmediate (/private/tmp/so/node_modules/mocha/lib/runner.js:258:5)
  at processImmediate [as _immediateCallback] (timers.js:330:15)

2) test fails async:
 Error: failed
  at /private/tmp/so/test/main.js:13:12
  at process._tickCallback (node.js:415:13)
like image 101
Miroslav Bajtoš Avatar answered Sep 17 '22 12:09

Miroslav Bajtoš