“fail”应该在jest测试的catch块中工作吗?或者:* 为什么 * 它不能在这个catch块中工作?

k10s72fa  于 2022-12-08  发布在  Jest
关注(0)|答案(1)|浏览(180)

我正在尝试使用try/catch和jest测试,发现了一些我不理解的行为。我的期望是fail('msg')应该在test("", () => { // fail should be available everywhere here }}的try/catch块中工作。
这让我觉得我不明白尝试/赶上我认为我做的方式。
下面是一些代码

import cats from "./script";

describe("try catch doesnt work for fail", () => {
    test("wherein we see fail doesn't work in try catch", () => {
        try {
            const x = cats()
            fail("cats")
            throw new Error("this fails")
        } catch(err){
            console.log(err)
            fail("isn't working in catch")
        }
    })
})

此错误消息如下:

● try catch doesnt work for fail › wherein we see fail doesn't work in try catch

    ReferenceError: fail is not defined

       9 |         } catch(err){
      10 |             console.log(err)
    > 11 |             fail("isn't working in catch")
         |             ^
      12 |         }
      13 |     })

请注意,它并没有说明try块中的fail("cats")
这到底是怎么回事?
请注意,这并没有阻止我的进步,更像是我只是好奇我对Jest的理解在哪里错了,也许JavaScript也是如此。
我在一个项目中发现了这一点:

ReferenceError: fail is not defined

      73 |             expect(true).toBe(true); 
                  // if "fail" isnt defined, why is "expect"?
      74 |             console.log(err);
    > 75 |             fail("some error2");
         |             ^
      76 |         }
      77 |     });
      78 | });

以下是一些可能无关的信息,但需要在本地进行设置:
.babelrc

{
    "presets": ["@babel/preset-env"]
  }

package.json

{
  "name": "sadf",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "jest"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/preset-env": "^7.20.2",
    "babel-jest": "^29.3.1",
    "jest": "^29.3.1"
  },
  "jest": {
    "transform": {
      "^.+\\.[t|j]sx?$": "babel-jest"
    }
  }
}

编辑:关于如何使测试失败here有一些类似问题
我不是在问如何使测试失败。我知道:在定义fail()的地方使用它。
问题是 * 是怎么回事 * 使fail()try中暴露而不在catch中暴露?我在这里了解到它是故意不在catch块中暴露的。但是,我还没有了解如何在try而不是catch中暴露fail()。这部分对我来说仍然是一个谜。
我希望我没有要求太多:没有人需要去弄清楚"Jest"究竟是如何安排了这种情况的,因为这可能需要大量的挖掘。这更像是"这怎么可能完成?"
edit2:IMO我的初衷,即"了解为什么fail()在try内可用,但在catch内不可用"根本没有被"重复"链接解决。

z0qdvdin

z0qdvdin1#

catch不能失败。它不是try块的一部分--没有什么可以失败的。您需要使用throw()来代替。

相关问题