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

如何在Jest中严格匹配数组中的对象?

在Jest中严格检查数组是否包含完全匹配结构的对象

你当前的代码通过expect.objectContaining做的是部分属性匹配——只要对象包含指定属性就会通过,不会校验是否存在额外属性,所以即使数组里的对象多了phone字段,断言也不会报错。要实现类似toStrictEqual结合arrayContaining的严格匹配效果,有以下几种可行方案:

方案1:用expect.arrayContaining配合expect.toStrictEqual

直接在arrayContaining中使用toStrictEqual指定严格匹配的对象,数组中必须存在一个与目标对象完全一致(属性数量、类型、值全部匹配)的元素才能通过断言:

const myArray = [{ name: 'Mete', age: 19, phone: '123456' }];
const targetObj = { name: 'Mete', age: 19 };

expect(myArray).toEqual(
  expect.arrayContaining([
    expect.toStrictEqual(targetObj)
  ])
);

// 此时会抛出错误,符合预期——数组对象多了phone属性,不满足严格匹配

方案2:自定义匹配器(更易用)

如果需要多次进行这类检查,自定义一个toContainStrictEqual匹配器能让代码更简洁直观:

// 扩展Jest内置匹配器
expect.extend({
  toContainStrictEqual(received, expected) {
    const pass = received.some(item => {
      // 复用Jest的严格比较逻辑
      return this.equals(item, expected, { isStrict: true });
    });

    if (pass) {
      return {
        message: () => `expected array not to contain strictly equal object: ${this.utils.printExpected(expected)}`,
        pass: true
      };
    } else {
      return {
        message: () => `expected array to contain strictly equal object: ${this.utils.printExpected(expected)}, but no match found`,
        pass: false
      };
    }
  }
});

// 使用自定义匹配器
const myArray = [{ name: 'Mete', age: 19, phone: '123456' }];
expect(myArray).toContainStrictEqual({ name: 'Mete', age: 19 });

// 抛出错误,符合预期

方案3:手动遍历验证

如果不想扩展匹配器,也可以手动遍历数组,结合try/catch用toStrictEqual逐个验证:

const myArray = [{ name: 'Mete', age: 19, phone: '123456' }];
const targetObj = { name: 'Mete', age: 19 };

const hasStrictMatch = myArray.some(item => {
  try {
    expect(item).toStrictEqual(targetObj);
    return true;
  } catch {
    return false;
  }
});

expect(hasStrictMatch).toBe(true);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 13:15:41