开玩笑:应该抛出的函数没有通过,测试将失败

Jest: function that should throw does not pass and test will fail

我想测试一个函数 A,该函数调用内部的多个其他函数可能会引发错误。

这是我的代码的抽象:

// file A.ts

const A = (args: any[]): boolean => {

   (() => {
      // nested function which throws
      throw new RangeError("some arg not correct")
   })()

   return true
}

// file main.test.ts

test("should throw an error", () => {

   expect(A()).toThrow()

})

如何在 Jest 中适当地测试它?

测试不会成功,jest 将记录抛出的错误。 这是一个 sandbox,这是测试的输出,你可以看到你是否 运行 test:

我不擅长打字稿,所以我用普通的 JS 写了例子。

原来是你do not need to call the A function to test if it throws:

// throw.test.js
const A = () => {
  (() => {
    // nested function which throws
    throw new RangeError("some arg not correct")
  })();
};


test("should throw an error", () => {
  expect(A).toThrow();
})

输出

> jest
 PASS  ./throw.test.js
  ✓ should throw an error (6ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.404s
Ran all test suites.

如果你确实想调用函数,比如说传递一个参数,在传递给期望的另一个函数中调用它:

// throw2.test.js
const A = () => {
  (() => {
    // nested function which throws
    throw new RangeError("some arg not correct")
  })();
};


test("should throw an error", () => {
  expect(() => A('my-arg')).toThrow();
})

我重构了一个异步函数,使其不再异步,但出现了这个错误。所以,如果你有一个 inner-async 函数,使用这个方法:

test("async function throws", async() => {
    await expect(() => A('my-arg')).rejects.toThrow();
})

您还可以进行一些更具体的检查,例如错误类型和消息等。

test("async function throws", async() => {
    await expect(() => A('my-arg')).rejects.toThrow(MyError("Specific Error Message");
})