jest 无法识别 URL 构造函数抛出的 TypeError

2024-01-01

Jest .toThrow(TypeError)与抛出的 TypeError 不匹配new URL构造函数。
这是一个错误还是我做错了什么?
笑话版本是29.4.2

测试用例:

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

输出是:

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

似乎这是 Node.js/Jest 中长期存在的错误,它与以下内容相关:

  • https://github.com/facebook/jest/issues/10045 https://github.com/facebook/jest/issues/10045
  • https://github.com/facebook/jest/issues/2549 https://github.com/facebook/jest/issues/2549
  • https://github.com/nodejs/node/issues/31852 https://github.com/nodejs/node/issues/31852
  • https://github.com/nodejs/node/issues/46558 https://github.com/nodejs/node/issues/46558

在我的机器上使用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"

即使你跑

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

使用节点你会得到true但是如果你将其添加到你的测试中并使用 Jest 运行它们,你就会得到false.

这表明 Error 对象不相同。


现在,我相信您可以创建自定义错误并在 URL 无效时抛出它,然后您可以在测试中使用该错误类型

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

jest 无法识别 URL 构造函数抛出的 TypeError 的相关文章

随机推荐