0

I want to assert a promise rejection in a mocha test case. Hence I do this in typescript:

import {
    expect,
    use,
} from "chai";
import * as chaiAsPromised from "chai-as-promised";

use(chaiAsPromised);

describe("Promise rejection", async () => {

    it("should assert promise rejection", async () => {
        const msg = "I AM THE EXPECTED ERROR";

        const rejectedPromise = Promise.reject(msg);

        return expect(rejectedPromise).to.eventually.throw(msg);

    });
});

I expect my test case to be successful, as the expected error is thrown. Yet my test fails with:

Error: the string "I AM THE EXPECTED ERROR" was thrown, throw an Error :)
    at <anonymous>
    at runMicrotasksCallback (internal/process/next_tick.js:122:5)
    at _combinedTickCallback (internal/process/next_tick.js:132:7)
    at process._tickCallback (internal/process/next_tick.js:181:9)
k0pernikus
  • 60,309
  • 67
  • 216
  • 347
  • What promise library are you using? In case of Bluebird, this is [a normal warning](http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-rejected-with-a-non-error) - you [should reject with `Error`s not with strings](https://stackoverflow.com/q/26020578/1048572). – Bergi Feb 20 '19 at 18:17

1 Answers1

0

You want to test for a promise rejection, not an error. Hence use rejectedWith:

return expect(rejectedPromise).to.eventually.be.rejectedWith(msg);
k0pernikus
  • 60,309
  • 67
  • 216
  • 347