当前位置: 首页 > 知识库问答 >
问题:

如何测试异常抛出使用Jest[重复]

茅和玉
2023-03-14

假设我有以下功能:

const filterByTerm = (inputArr, searchTerm) => {
    if(!inputArr.length) throw Error("inputArr can not be empty");
    if(!searchTerm) throw Error("searchTerm can not be empty");

    const regex = RegExp(searchTerm, "i");
    return inputArr.filter(it => it.url.match(regex));
}

根据Jest文档,我应该能够使用以下代码测试函数是否引发异常:

const filterByTerm = require("../src/filterByTerm");

describe("Filter function", () => {

    test("it should throw and error if inputArr is empty", () => {
        expect(filterByTerm([], "link")).toThrow(Error);
    });

    test("it should throw and error if searchTerm is empty", () => {
        expect(filterByTerm(["a", "b", "c"], "")).toThrow(Error);
    });

});

但是,我得到了以下错误。

 FAIL  __tests__/filterByTerm.spec.js
  Filter function
    ✓ it should filter by a search term (link) (3ms)
    ✓ it should return an empty array if there is an empty search term (1ms)
    ✕ it should throw and error if inputArr is empty (2ms)
    ✕ it should throw and error if searchTerm is empty (1ms)

  ● Filter function › it should throw and error if inputArr is empty

    inputArr can not be empty

      1 | const filterByTerm = (inputArr, searchTerm) => {
    > 2 |     if(!inputArr.length) throw Error("inputArr can not be empty");
        |                                ^
      3 |     if(!searchTerm) throw Error("searchTerm can not be empty");
      4 | 
      5 |     const regex = RegExp(searchTerm, "i");

      at filterByTerm (src/filterByTerm.js:2:32)
      at Object.<anonymous> (__tests__/filterByTerm.spec.js:35:16)

  ● Filter function › it should throw and error if searchTerm is empty

    searchTerm can not be empty

      1 | const filterByTerm = (inputArr, searchTerm) => {
      2 |     if(!inputArr.length) throw Error("inputArr can not be empty");
    > 3 |     if(!searchTerm) throw Error("searchTerm can not be empty");
        |                           ^
      4 | 
      5 |     const regex = RegExp(searchTerm, "i");
      6 |     return inputArr.filter(it => it.url.match(regex));

      at filterByTerm (src/filterByTerm.js:3:27)
      at Object.<anonymous> (__tests__/filterByTerm.spec.js:40:16)

有人能告诉我我做错了什么吗?

谢谢!

共有1个答案

郎弘业
2023-03-14

当您想要捕获抛出的错误时,您必须传递期望函数:

expect(() => filterByTerm(["a", "b", "c"], "")).toThrow(Error);
 类似资料:
  • 我正在处理一些代码,需要测试函数抛出的异常类型(是TypeError、ReferenceError等吗?)。 我当前的测试框架是AVA,我可以将其作为第二个参数方法进行测试,如下所示: 我开始用笑话重写我的测试,但找不到如何轻松做到这一点。这有可能吗?

  • 我用Spock测试Java代码。我测试这段代码: 我写了一个测试: 它失败是因为抛出了另一个CustomException。但是在块中,我捕获这个异常并抛出一个,因此我希望我的方法将抛出,而不是。如何测试它?

  • 试图利用本SO帖子中概述的方法。 我有以下类型的例外: 这个函数抛出它: 这项工作: 但这并不: 有人知道为什么后者不起作用吗?笑话日志:

  • 我知道一种方法是: 有什么更干净的方法吗?(可能使用JUnit的?)

  • 我有一个方法: 这是用户授权测试的样子: 有没有办法检查用户输入错误密码的情况?因为在我发送错误密码的情况下,它不起作用,因为 使在你检查密码之前返回结果。

  • 我有一个类,它有一个方法。我正在做相应的测试,但是我还不能验证是否抛出了定制的异常,我使用的是JUnit5。 我已经复习了这里,但答案并没有帮助我,这是我根据一个示例编写的代码: