参数化Jest的期望

时间:2019-01-26 13:25:32

标签: node.js unit-testing jestjs

由于operator precedence会在Jest尝试捕获之前抛出,因此我无法传递抛出expect()的函数。

所以代替这个:

expect(thisThrows())

我们必须这样做:

expect(() => thisThrows())

但是说我想参数化它:

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();
});

这仍然是原始问题。

我该如何整齐地做这样的事情,以便我的测试保持干燥?

1 个答案:

答案 0 :(得分:3)

由于sut()引发错误,因此不能直接将其称为expect(sut(undefined),因为该错误会立即引发并且无法断言。

应该与expect(() => thisThrows())一样对待:

expect(() => sut(undefined)).toThrow();