I'm following a simple jest tutorial. I have a function that looks like this:
function filterByTerm(inputArr, searchTerm) {
if (!inputArr.length) throw Error("input array cannot be empty");
if (searchTerm) {
const regex = new RegExp(searchTerm, "i");
return inputArr.filter(function (arrayElement) {
return arrayElement.url.match(regex);
});
}
return [];
}
module.exports = filterByTerm;
and a jest test suite that looks like this:
const filterByTerm = require("../src/filterByTerm");
describe("Filter function", () => {
const input = [
{ id: 1, url: "https://www.url1.dev" },
{ id: 2, url: "https://www.url2.dev" },
{ id: 3, url: "https://www.link3.dev" },
];
const output = [{ id: 3, url: "https://www.link3.dev" }];
const urlOutput = [
{ id: 1, url: "https://www.url1.dev" },
{ id: 2, url: "https://www.url2.dev" },
];
test("It should filter by a search term (link)", () => {
expect(filterByTerm(input, "link")).toEqual(output);
expect(filterByTerm(input, "LINK")).toEqual(output);
});
test("It should filter by a search term (uRl)", () => {
expect(filterByTerm(input, "uRl")).toEqual(urlOutput);
});
test("It should not return anything on an empty search term", () => {
expect(filterByTerm(input, "")).toEqual([]);
});
test("An empty input array should trigger an error", () => {
expect(() =>
filterByTerm([], "link").toThrowError(
new Error("input array cannot be empty")
)
);
});
test("No inputs should throw a new error", () => {
expect(() =>
filterByTerm().toThrowError(new Error("input array cannot be empty"))
);
});
});
When I run my tests, they all report as passed, but when I review my coverage, I see that line 2 of my filter by term function is not covered so far as Jest is concerned.
My understanding is that the final two test cases ("An empty input array should trigger an error" and "no inputs should throw a new error") ought to be testing line 2 of filterByTerm, since they both are expecting the error that it throws, but that does not appear to be the case.
Why doesn't Jest consider this line as "covered"? What should I do to properly cover it?