1

Given I have the following function:

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

According to Jest documentation, I should be able to test that the function throws Exceptions with the following code:

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

});

However, I'm getting the following errors.

 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)

Can someone tell me what I'm doing incorrectly?

Thanks!

skyboyer
  • 22,209
  • 7
  • 57
  • 64
  • Does this answer your question? [How to test type of thrown exception in Jest](https://stackoverflow.com/questions/46042613/how-to-test-type-of-thrown-exception-in-jest) – Paul Parker Mar 10 '20 at 23:52
  • Use: `expect(() => filterByTerm([], "link")).toThrow(Error);` – Paul Parker Mar 10 '20 at 23:54

1 Answers1

0

You have to pass expect a function when you want to catch an error being thrown:

expect(() => filterByTerm(["a", "b", "c"], "")).toThrow(Error);
Nick
  • 16,066
  • 3
  • 16
  • 32