鉴于我具有以下功能:
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));
}
根据笑话documentation,我应该能够使用以下代码测试该函数引发Exceptions:
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)
有人可以告诉我我做错了什么吗?
谢谢!
答案 0 :(得分:0)
要捕获抛出的错误,必须传递expect
一个函数:
expect(() => filterByTerm(["a", "b", "c"], "")).toThrow(Error);