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

为何Jest的toStrictEqual无法匹配fetch API返回的JSON响应?

Jest中toStrictEqual测试失败但toEqual正常的原因

相关代码

路由代码

debug.get('/echo', (req, res) => {
  const { value } = req.query;
  console.log(`[ ECHO ] ${value}`);
  res.json({ value });
});

测试代码

it('echoes the given content', async () => {
  const res = await fetch(`${URL}/debug/echo?value=hello`);
  const data = await res.json();
  expect(data).toStrictEqual({ value: 'hello' });
});

测试失败提示

FAIL  tests/debug.test.ts

  ● /debug/echo › echoes the given content

    expect(received).toStrictEqual(expected) // deep equality

    Expected: {"value": "hello"}
    Received: serializes to the same string

       8 |     const data = await res.json();
       9 |     console.log(data);
    > 10 |     expect(data).toStrictEqual({ value: 'hello' });
         |                  ^
      11 |   });
      12 | });
      13 |

      at Object.toStrictEqual (tests/debug.test.ts:10:18)

原因分析

问题核心在于Jest两个断言方法的严格程度差异:

  • toEqual仅做深层值对比,只要对象的结构、嵌套值完全匹配就通过,会忽略原型链、属性描述符(可写性、可枚举性等)这类元信息。
  • toStrictEqual是严格深层相等检查,除了比对值,还会验证:
    • 对象的原型链是否完全一致
    • 属性是否为对象自身拥有(通过hasOwnProperty判断)
    • 属性的描述符(可写、可枚举、可配置等特性)是否完全相同

这个场景里,fetch的res.json()返回的对象是通过JSON.parse解析生成的(部分测试环境的fetch实现可能会对其做额外包装),它和字面量创建的{ value: 'hello' }值完全一致,但在原型链或属性描述符上存在细微差异——虽然序列化后的字符串完全相同,但这些元信息的不同触发了toStrictEqual的失败。而toEqual忽略这些元信息,只比对值,所以能正常通过测试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 11:20:01