【问题标题】:How to test exceptions are being thrown using Jest [duplicate]如何使用 Jest 测试抛出异常 [重复]
【发布时间】:2020-06-22 22:19:12
【问题描述】:

鉴于我有以下功能:

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 documentation,我应该能够使用以下代码测试该函数是否抛出异常:

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)

谁能告诉我我做错了什么?

谢谢!

【问题讨论】:

标签: javascript jestjs


【解决方案1】:

当你想捕捉抛出的错误时,你必须传递expect 一个函数:

expect(() => filterByTerm(["a", "b", "c"], "")).toThrow(Error);

【讨论】:

    猜你喜欢
    • 2018-09-11
    • 2018-02-13
    • 2012-11-19
    • 2018-12-10
    • 2020-11-24
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    相关资源
    最近更新 更多