You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Jest模拟抛出异常?下述EmailValidatorAdapter测试存在什么问题?

测试代码的问题分析

你的测试代码存在两个核心问题:

1. 提前执行了会抛出异常的方法,导致测试直接崩溃

你直接执行了 const response = sut.isValid('invalid@email.com'),这行代码会立刻触发内部校验器的异常,代码会直接抛出错误终止,根本走不到后续的 expect 断言逻辑。

2. toThrow 的用法错误

expect(response).toThrow() 是错误的写法,toThrow 断言需要接收一个未执行的函数(或者返回函数的回调),用来检测这个函数执行时是否会抛出异常,而不是接收一个已经执行后的变量值。

修正后的测试代码

test('should throws if validator throws', () => {
  const sut = new EmailValidatorAdapter()
  jest.spyOn(validator, 'isEmail').mockImplementationOnce(() => {
    throw new Error()
  })
  // 用回调包裹要测试的方法,避免提前执行抛出异常
  expect(() => sut.isValid('invalid@email.com')).toThrow()
})

内容的提问来源于stack exchange,提问作者Silas Paixão

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 15:43:10