在 Jest 中测试错误处理和异常情况是确保代码健壮性的重要部分:
1. 测试同步函数抛出错误:
javascripttest('throws error when invalid input', () => { expect(() => divide(10, 0)).toThrow(); expect(() => divide(10, 0)).toThrow('Division by zero'); expect(() => divide(10, 0)).toThrow(/zero/); });
2. 测试 Promise 拒绝:
javascripttest('rejects when API fails', async () => { await expect(fetchData()).rejects.toThrow('API Error'); }); // 或使用 .catch test('rejects when API fails', async () => { await expect(fetchData()).rejects.toEqual({ message: 'API Error' }); });
3. 测试异步回调中的错误:
javascripttest('callback with error', (done) => { fetchData((err, data) => { expect(err).toBeInstanceOf(Error); expect(err.message).toBe('Network error'); done(); }); });
4. 测试自定义错误类型:
javascripttest('throws custom error', () => { expect(() => validate(null)).toThrow(ValidationError); });
5. 使用 try-catch 测试:
javascripttest('handles error gracefully', async () => { try { await riskyOperation(); fail('Should have thrown an error'); } catch (error) { expect(error).toBeInstanceOf(Error); expect(error.message).toContain('failed'); } });
6. 测试错误边界(React):
javascripttest('ErrorBoundary catches errors', () => { const consoleSpy = jest.spyOn(console, 'error').mockImplementation(() => {}); render( <ErrorBoundary> <ThrowingComponent /> </ErrorBoundary> ); expect(screen.getByText('Something went wrong')).toBeInTheDocument(); consoleSpy.mockRestore(); });
最佳实践:
- 明确测试错误消息和类型
- 使用
toThrow()匹配错误消息或正则表达式 - 测试错误处理逻辑,而不仅仅是错误本身
- 确保清理 Mock 和 Spy
- 测试边界情况和无效输入