0

Objective

Run Mocha tests with npm run, without getting a ELIFECYCLE error.

Background

After my last question on mocha and npm, I found that Mocha returns the number of failed tests as a result.

Now, when running a script with npm (via npm run), the script must return 0, or the npm will throw a ELIFECYCLE error and crash the execution of the script.

Problem

This is obviously incredibly dumb cumbersome, as when developing code, tests are supposed to fail. This is normal, and we don't want the code to crash every single time we miss an assertion.

This pretty much forces me to re-launch everything, and what I find mind blowing is that in previous versions of npm, this crashing behavior was not present.

Currently I am using npm version 3.10.3.

What I tried

After reading npm error ELIFECYCLE while running the test I see one possible solution. But since this one solution will suppress all kinds of errors (even the ones that should crash the app) I would rather not implement it.

Questions

  • How can I run my tests in Mocha (knowing that some will fail) without completely crashing the whole application with a ELIFECYCLE error?
  • Is this issue fixed in more recent versions of npm? (What is the most recent version, since I can't find it anywhere?)

Any help with this will be most appreciated.

Community
  • 1
  • 1
Flame_Phoenix
  • 16,489
  • 37
  • 131
  • 266

2 Answers2

0

have you considered to run mocha from your code in the following way:

const Mocha = require('mocha');

module.exports = () => {
  // Instantiate a Mocha instance.
  const mocha = new Mocha({
    ui: 'bdd',
    fullTrace: true,
  });

  const testDir = 'test/spec';

  config.getGlobbedFiles(`${testDir}/**/*.spec.js`, './').forEach((filePath) => {
    mocha.addFile(filePath);
  });

  // Run the tests.
  mocha.run((failures) => {
    process.exit(failures);  // exit with non-zero status if there were failures
  });
};

and in order to run it from gulp you can use:

const minimist = require('minimist');

const knownOptions = {
  string: 'params',
  default: {
    params: '',
  },
};
const options = minimist(process.argv.slice(2), knownOptions);

...

gulp.task('test', () => {
  if (process.env.NODE_ENV !== 'test') {
    throw new Error('Wrong NODE_ENV value. Tests must be ran with "test"');
  }
  // eslint-disable-next-line import/no-dynamic-require, global-require
  return require('test/test')(options.params); // where `test/test` is test runner above
});
vedi
  • 400
  • 3
  • 17
0

I haven't tested this but I think if you update your script to something like:

"test": "mocha || true"

It will return code 0 on a failure.

Brandon Parker
  • 762
  • 7
  • 18