Nekron SN
Nekron SN

Reputation: 101

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.

Upvotes: 2

Views: 1019

Answers (1)

Mike
Mike

Reputation: 1375

.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
  });
});

Upvotes: 1

Related Questions