Jest.js 如何用笑话来嘲笑投掷

k4emjkb1  于 9个月前  发布在  Jest
关注(0)|答案(2)|浏览(116)

下面这个测试有什么问题?

test('should throws if validator throws', () => {
      const sut = new EmailValidatorAdapter()
      jest.spyOn(validator, 'isEmail').mockImplementationOnce(() => {
          throw new Error()``
    })
      const response = sut.isValid('[email protected]')
      expect(response).toThrow()
  })

字符串
我试图确保EmailValidatorAdapter抛出,如果它的电子邮件验证器依赖抛出。所以,我将在控制器层治疗。

xzlaal3s

xzlaal3s1#

如果sut.isValid()调用validator.isEmail(),您提供的mock实现将抛出异常,sut.isValid()永远不会返回,response不会被设置,expect(response).doWhatever()也不会被执行。相反,Jest会捕获异常并得出测试失败的结论。
当你期望抛出异常时,你不需要自己调用函数,而是将抛出异常的函数或调用抛出异常的函数的函数传递给expect(),然后expect()为你调用它。
就像这样:

it('throws if validator throws', () => {
  const sut = new EmailValidatorAdapter()
  jest.spyOn(validator, 'isEmail').mockImplementationOnce(() => {
    throw new Error();
  });

  expect(() => sut.isValid('[email protected]')).toThrow();
});

字符串

1cosmwyk

1cosmwyk2#

你可以这样说,它通常为我工作。

test('should throws if validator throws', () => {
  const sut = new EmailValidatorAdapter()
  jest.spyOn(validator, 'isEmail').mockImplementationOnce(() => {
    throw new Error()
  })
  const response = sut.isValid('[email protected]')
  expect(response).toEqual(new Error('error_text'))
})

字符串
可以将new Error('error_text')更改为您试图模拟的异常,如new BadRequestException('error_text')

相关问题