Search code examples
typescriptpromisemocha.jschaichai-as-promised

Why is my expected rejection not a success case in mocha using chai-as-promise?


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)

Solution

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

    return expect(rejectedPromise).to.eventually.be.rejectedWith(msg);