Parameterize Jest's expect

2019-06-05 00:57发布

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?

1条回答
放我归山
2楼-- · 2019-06-05 01:37

Since sut() throws an error, it cannot be called directly as expect(sut(undefined) because the error is thrown immediately and it cannot be asserted.

It should be treated the same way as with expect(() => thisThrows()):

expect(() => sut(undefined)).toThrow();
查看更多
登录 后发表回答