3
votes

So I have this code, createExampleDir is not yet implemented, so the test fails:

let chai    = require('chai');
let expect  = chai.expect;
let homeDir = require('home-dir');
let lib     = require('../lib.js');

chai.use(require('chai-fs'));

let dir     = homeDir('/example-dir');

describe('lib', () =>
  describe('createExampleDir', () =>
    it('should find ~/example-dir', () => lib.createExampleDir()
      .then(() => expect(dir).to.be.a.directory())
      .catch(() => {throw Error('Who cares!');})
    )
  )
);

The problem is that I'm getting an UnhandledPromiseRejectionWarning error, the error "Who cares!" is throw, so the catch happens:

(node:30870) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): [object Object] (node:30870) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

What should I do to avoid the UnhandledPromiseRejectionWarning warning?

1
The catch block is entered because lib. createExampleDir is undefined. Then you throw from there. That is not handled. What you should do, is obvious from there: catch the Who cares error in an outer catch block.marekful
Thanks @marekful, I'm still new to promises and async, I didn't understand your comment.Nabil Kadimi
"the error "Who cares!" is thrown, so the catch happens" - no, it's exactly the other way round. Some error is happening, so the catch callback gets invoked, which then throws the "Who cares" exception that isn't handled anywhere.Bergi

1 Answers

0
votes

add this code after chai.use

process.on('unhandledRejection', e => {
  console.error(e);
});

And you can catch error and code string number.