'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.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source