user3137766
user3137766

Reputation:

Test a simple function with jest

I want to test one simple function with Jest :

// src > filterByTerm.js
function filterByTerm(inputArr, searchTerm) {
    if (!searchTerm) throw Error("searchTerm cannot be empty");
    if (!inputArr.length) throw Error("inputArr cannot be empty"); // new line

    const regex = new RegExp(searchTerm, "i");
    return inputArr.filter(function(arrayElement) {
      return arrayElement.url.match(regex);
    });
 }
 module.exports = filterByTerm;

 // filterByTerm.spec.js

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

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

   test("it should output error", () => {
        const input = [
          { id: 1, url: "https://www.url1.dev" },
          { id: 2, url: "https://www.url2.dev" },
          { id: 3, url: "https://www.link3.dev" }
        ];
        expect(filterByTerm(input, "")).toThrowError();
      });
 });

My Question is, why this test not passing? how to catch error from Jest ?

Thank you

Upvotes: 0

Views: 277

Answers (3)

Alexander Campbell
Alexander Campbell

Reputation: 11

Try wrapping your expect function in another function call:

Instead of:

expect(filterByTerm(input, "")).toThrowError(errorMessage);

Try:

expect(() => filterByTerm(input, "")).toThrow(errorMessage);

where errorMessage is whatever Error you're throwing.

Upvotes: 1

user12703428
user12703428

Reputation: 11

You need to alter the function so try something like this;

const output = [{id: 3, url: "https://www.link3.dev"}]; expect(() => { input(''); }).toThrow(Error);

and alter the function to this;

if (!searchTerm) throw Error("searchTerm cannot be empty");


if (!inputArr.length) throw Error("inputArr cannot be empty");

Upvotes: 0

Narendra
Narendra

Reputation: 4574

I believe you should do

if (!searchTerm) throw new Error("searchTerm cannot be empty");

and

expect(filterByTerm(input, "")).toThrowError("searchTerm cannot be empty");

You can further read here.

Upvotes: 0

Related Questions