Skip to content

Instantly share code, notes, and snippets.

@haroldtreen
Last active August 25, 2023 13:59
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save haroldtreen/5f1055eee5fcf01da3e0e15b8ec86bf6 to your computer and use it in GitHub Desktop.
Save haroldtreen/5f1055eee5fcf01da3e0e15b8ec86bf6 to your computer and use it in GitHub Desktop.
Testing promise rejection with Mocha
const { assert } = require('chai');
function isError(e) {
if (typeof e === 'string') {
return Promise.reject(new Error(e));
}
return Promise.resolve(e);
}
describe('Promise Testing', () => {
// With done callback - 8 lines
it('should test rejections using done', (done) => {
aMethodThatRejects()
.then(() => {
done(new Error('Expected method to reject.'))
})
.catch((err) => {
assert.isDefined(err);
done();
})
.catch(done);
});
// With built in Promise support - 8 lines + helper
it('should test rejections using catch', () => {
return aMethodThatRejects()
.then(() => {
return Promise.reject('Expected method to reject.');
})
.catch(isError)
.then((err) => {
assert.isDefined(err);
});
});
});
@naptowncode
Copy link

it('should test rejections using then', () => {
  return aMethodThatRejects()
    .then(
      () => Promise.reject(new Error('Expected method to reject.')),
      err => assert.instanceOf(err, Error)
    );
});

People often forget that .then(onFulfilled) is actually .then(onFulfilled[, onRejected]).

@iamdanthedev
Copy link

thanks @naptowncode, this is really the best solution

@adrian-gierakowski
Copy link

@iamdanthedev, consider:

chai = require('chai')
  .use(require('chai-as-promised'))

expect = chai.expect
  
it('should test rejections using then', () => {
  return expect(aMethodThatRejects()).to.be.rejectedWith(ErrorClass, "message")
});

there is similar functionality Jests expect and in power-assert

and if you are running on node 10, there is native assert.rejects

@jfavrod
Copy link

jfavrod commented Dec 19, 2019

Using node's assert module I was able to do this:

    it('Should reject on bad values', async () => {
            const badValues = async () => {
                // A method the rejects when given a bad argument.
                myMethod('bad argument');
            }

            assert.rejects(badValues);
    });

@dolad
Copy link

dolad commented Aug 25, 2023

@jfavrod this does not assert on error message.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment