I can't pass a function that throws into expect()
as due to operator precedence that will throw before Jest can try-catch it.
So instead of this:
expect(thisThrows())
We must do this:
expect(() => thisThrows())
But say I want to parameterize it:
test("foo", () => {
const sut = (arg) => { if (!arg) throw new Error(); };
expect(sut(undefined)).toThrow();
expect(sut(null)).toThrow();
expect(sut(0)).toThrow();
expect(sut("")).toThrow();
expect(sut(10)).not.toThrow();
});
This still has the original problem.
How can I do something like this neatly, so I can keep my tests DRY?
Since
sut()
throws an error, it cannot be called directly asexpect(sut(undefined)
because the error is thrown immediately and it cannot be asserted.It should be treated the same way as with
expect(() => thisThrows())
: