参数化Jest的期望 [英] Parameterize Jest's expect

查看:129
本文介绍了参数化Jest的期望的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于运算符优先级,该函数将抛出Jest,因此我无法传递引发expect()的函数可以尝试捕获它.

I can't pass a function that throws into expect() as due to operator precedence that will throw before Jest can try-catch it.

所以代替这个:

expect(thisThrows())

我们必须这样做:

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

这仍然是原始问题.

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

How can I do something like this neatly, so I can keep my tests DRY?

推荐答案

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

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.

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

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

这篇关于参数化Jest的期望的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆