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

如何在Jest中测试stringify函数的catch代码块?

如何测试JSON.stringify封装函数的catch代码块?

问题场景

我有一个基础的stringify函数,封装了JSON.stringify并做了异常捕获:

export const stringify = <T>(value: T) => {
  try {
    return JSON.stringify(value);
  } catch(error){
    return ''
  }
}

我想编写测试用例覆盖它的catch代码块,试了下面的测试代码:

it('should be able to check for errors', async () => {
  await expect(stringify('')).rejects.toThrow()
})

但测试一直报错,提示函数不是Promise,而且函数根本没进入catch代码块。因为主函数不是Promise,没法用Jest的Promise相关方法,请问该怎么测试catch代码块?

解决方案

核心要点

要触发JSON.stringify的异常,你需要传入无法被序列化的值,同时因为函数是同步的,直接断言返回值为空字符串即可,不用异步相关的断言方法。

具体测试用例

1. 测试循环引用对象

循环引用是JSON.stringify最典型的报错场景,用它能轻松触发catch块:

it('should return empty string for circular reference objects', () => {
  const circularObj: any = {};
  circularObj.self = circularObj; // 构造循环引用

  const result = stringify(circularObj);
  expect(result).toBe('');
})

2. 测试带有报错toJSON方法的对象

如果对象的toJSON方法抛出错误,JSON.stringify也会触发异常:

it('should return empty string when toJSON method throws', () => {
  const faultyObj = {
    toJSON: () => {
      throw new Error('Serialization failed');
    }
  };

  const result = stringify(faultyObj);
  expect(result).toBe('');
})

原测试无效的原因

  • 传入的空字符串''是合法的可序列化值,不会触发JSON.stringify异常,自然进不了catch块
  • 你的函数是同步函数,await和rejects是专门测试异步Promise的API,用在同步函数上必然报错

内容的提问来源于stack exchange,提问作者Parth

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 06:15:39