Search code examples
javascripttypescriptjestjstypeerrorts-jest

jest does not recognize TypeError thrown by URL constructor


Jest .toThrow(TypeError) does not match TypeError thrown by new URL constructor.
Is this a bug or am I doing something wrong?
Jest version is 29.4.2

Test case:

it("throws TypeError when url is invalid", () => {
  expect(() => {
    new URL(""); // This does not work
    // throw new TypeError(); // This works
  }).toThrow(TypeError);
})

Output is:

Expected constructor: TypeError
Received constructor: TypeError

Received message: "Invalid URL: "

      13 |     it("throws TypeError when url is invalid", () => {
      14 |         expect(() => {
    > 15 |             new URL("");
         |             ^
      16 |             // throw new TypeError();
      17 |         }).toThrow(TypeError);

Solution

  • Seems like it's a long standing bug in Node.js/Jest, and it's related to:

    On my machine using Node.js v16.19.0 and Jest v29.4.3 I got:

        expect(received).toThrow(expected)
    
        Expected constructor: TypeError
        Received constructor: TypeError
    
        Received message: "Invalid URL"
    

    Even if you run

    try {
      new URL("");
    } catch (error) {
      console.error(error instanceof TypeError);
    }
    

    With node you'll get true but if you add this to your tests and run them with Jest you'll have false.

    Which shows that the Error objects are not identical.


    For now, I believe that you can create your custom error and throw it when URLs are invalid, then you can use that error type in your tests