Reputation:
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
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
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