Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test a String thrown using Jest

I ran into a situation where a function throws a string.

I am aware that on jest we have the toThrow matcher that allows us to test that functions do in fact throw. But this matcher is only working when what is thrown is an Error.

Is it possible to verify that a String is thrown using Jest?

The following code

async function funToTest(): Promise<number> {
  if (Math.random()) throw 'ERROR_CODE_X';
  return 10;
}

describe('funToTest', () => {
  it('should throw `ERROR_CODE_X`', () => {
    await expect(() => funToTest()).rejects.toThrow('ERROR_CODE_X');
  });
});

returns

funToTest › should throw `ERROR_CODE_X`

    expect(received).rejects.toThrow(expected)

    Expected substring: "ERROR_CODE_X"

    Received function did not throw

Which clearly states that it did not throw while the function does throw.

And if we change it to be an Error (throw new Error('ERROR_CODE_X')), then it works.

like image 767
Nekron SN Avatar asked Mar 13 '26 16:03

Nekron SN


1 Answers

.reject make expect to test rejected value so you can use standard expect matches here

async function funToTest(): Promise<number> {
  throw "ERROR_CODE_X";
}
async function funToError(): Promise<number> {
  throw new Error("ERROR_CODE_X");
}

describe("funToTest", () => {
  it("should throw `ERROR_CODE_X`", async () => {
    //await expect(() => funToTest()).rejects.toThrowErrorMatchingSnapshot();
    // ^^^ not ok: undefined in snapshot
    await expect(() => funToTest()).rejects.toMatchSnapshot();
    await expect(() => funToTest()).rejects.toEqual("ERROR_CODE_X");
  });
  it("should not throw `ERROR_CODE_X`", async () => {
    await expect(() => funToError()).rejects.toThrowErrorMatchingSnapshot();

    await expect(() => funToError()).rejects.toEqual("ERROR_CODE_X");
    //fail here: rejects return a Error
  });
});
like image 197
Mike Avatar answered Mar 16 '26 05:03

Mike