Search code examples
javascriptunit-testingasynchronouses6-promise

Javascript Promises: testing error scenario


How do I test a promise that rejects with an error? (that is the expected behaviour)

I can not figure out why this test is failing. I'm catching the error rejected, and the test still fails. From the example provided at https://www.sitepoint.com/promises-in-javascript-unit-tests-the-definitive-guide/ this should work, and can't figure out how it's supposed to really. Both console logs appear.

    it('shows that even an error occurs the test passes', (done) => {
      const promise = new Promise((resolve, reject) => {
        console.log('error promise is called');
        setTimeout(() => {
          reject(new Error('dummy error thrown'));
        }, 100);
      })

      promise.then(() => {});

      promise.catch((e) => {
        console.log('error caught');
        done();
      });
    });
1) promise behaviour in tests (async) -  base test cases shows that even an error occurs the test passes:
     Uncaught Error: dummy error thrown
      at Timeout.setTimeout [as _onTimeout] (test\promise-spec.js:24:17)

Tried like this, still fail

      promise
        .then(() => {})
        .catch((e) => {
          console.log('error caught');
          done();
        });


Solution

  • Turns out it was because of a previous test that didn't call done, and it throwing an error killed this one