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

如何利用Jest原生功能验证两个JSON字符串对应同一对象?

验证JSON字符串是否对应同一对象的Jest实现方式

Jest本身没有原生匹配器可以直接验证两个JSON字符串是否对应同一个语义对象(忽略键顺序),但可以通过两种简洁方式实现需求:

1. 自定义匹配器(提升测试代码可读性)

你可以通过expect.extend自定义一个toMatchJSON匹配器,封装JSON解析和对象比较逻辑,后续测试可直接调用:

// 在测试文件顶部或Jest配置的setup文件中定义
expect.extend({
  toMatchJSON(received, expected) {
    try {
      const parsedReceived = JSON.parse(received);
      const parsedExpected = JSON.parse(expected);
      const pass = this.equals(parsedReceived, parsedExpected);

      if (pass) {
        return {
          message: () => `预期JSON字符串不匹配:${expected}`,
          pass: true
        };
      } else {
        return {
          message: () => `预期JSON字符串匹配:${expected}\n但解析后的值为:${JSON.stringify(parsedReceived, null, 2)}`,
          pass: false
        };
      }
    } catch (err) {
      return {
        message: () => `存在无效JSON:${err.message}`,
        pass: false
      };
    }
  }
});

// 测试用例中使用
test('Hasura Claims JSON语义匹配', () => {
  const actualClaim = '{"x-hasura-role":"user","x-hasura-user-id":"123"}';
  const expectedClaim = '{"x-hasura-user-id":"123","x-hasura-role":"user"}';
  expect(actualClaim).toMatchJSON(expectedClaim);
});

2. 直接组合原生功能(无需额外定义)

如果不想自定义匹配器,也可以直接在expect中组合JSON.parse和toEqual,这是完全基于Jest原生功能的写法:

test('Hasura Claims解析后匹配', () => {
  const actualClaim = '{"x-hasura-role":"user","x-hasura-user-id":"123"}';
  const expectedClaim = '{"x-hasura-user-id":"123","x-hasura-role":"user"}';
  expect(JSON.parse(actualClaim)).toEqual(JSON.parse(expectedClaim));
});

这种方式本质和你当前的实现一致,但写法更紧凑,依赖Jest原生的toEqual(会递归比较对象属性,自动忽略键顺序)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 15:45:06