tothrow 是 jest 中测试函数抛出异常的匹配器,需用 expect(() => fn()).tothrow() 包裹被测函数;支持验证任意错误、精确/模糊匹配错误消息、断言错误类型,异步场景须用 rejects.tothrow()。

toThrow 是 Jest 中专门用于测试函数是否抛出异常的匹配器,必须配合 expect(...).toThrow() 使用,且被测函数必须以 expect(() => fn()).toThrow(...) 的方式包裹在箭头函数中,否则错误会在断言执行前就抛出,导致测试直接失败。
基本用法:验证是否抛出任意错误
只要函数执行时抛出任何错误(无论类型或消息),断言即通过:
test('should throw when input is empty', () => {
const fn = () => {
if (!''.length) throw new Error('Input required');
};
expect(fn).toThrow(); // ✅ 通过
});
验证错误消息(字符串或正则)
可传入字符串精确匹配 error.message,或传入正则表达式做模糊匹配:
- 字符串匹配:要求完全相等(区分大小写)
-
正则匹配:常用
/required/i忽略大小写,或/^Input.*required$/确保开头结尾
expect(fn).toThrow('Input required'); // ✅ 完全匹配
expect(fn).toThrow(/input.*required/i); // ✅ 正则匹配(忽略大小写)
验证错误构造函数类型(如 TypeError、CustomError)
传入构造函数(如 TypeError)可断言抛出的是指定类型的错误:
const badFn = () => { throw new TypeError('Invalid type'); };
expect(badFn).toThrow(TypeError); // ✅ 类型匹配
注意:toThrow(TypeError) 不校验消息内容,只关心 error instanceof TypeError 是否为真。
常见错误与注意事项
-
❌ 直接调用函数:
expect(fn()).toThrow()—— 错误立即抛出,测试中断 -
❌ 忘记箭头函数包裹:
expect(fn).toThrow()是对函数本身断言,不是对其执行结果 -
❌ 使用 async/await 时未适配:异步函数需用
rejects.toThrow(),而非toThrow()
// ✅ 异步函数正确写法
test('async fn throws', async () => {
const asyncFn = () => Promise.reject(new Error('Boom'));
await expect(asyncFn()).rejects.toThrow('Boom');
});











