【问题标题】:Parameterize Jest's expect参数化 Jest 的期望
【发布时间】:2019-06-20 02:04:02
【问题描述】:

我不能传递一个抛出到 expect() 的函数,因为 operator precedence 会在 Jest 尝试捕获它之前抛出。

所以不要这样:

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

这还是原来的问题。

我怎样才能巧妙地做这样的事情,这样我就可以保持我的测试干燥?

【问题讨论】:

    标签: node.js unit-testing jestjs


    【解决方案1】:

    由于sut()抛出错误,所以不能直接调用expect(sut(undefined),因为错误立即抛出,无法断言。

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

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

    【讨论】:

      猜你喜欢
      • 2020-06-26
      • 2020-05-01
      • 2019-04-10
      • 2014-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-12
      相关资源
      最近更新 更多