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

如何使用Jest严格测试objectContaining匹配器?

解决Jest中严格校验对象完整结构的问题

要实现像toStrictEquals那样严格校验对象的所有键与结构,同时保留使用匹配器(比如expect.stringContaining)的能力,可以通过以下两种原生方式实现:

方法一:拆分校验逻辑(推荐)

先获取 spy 的调用参数,分别校验对象的字段规则和键的完整性:

it('should work', () => {
  const spy = jest.fn();
  const obj = {
    hello: "world",
    foo: "bar",
  }

  spy(obj);

  // 获取 spy 的第一个调用参数
  const [callArg] = spy.mock.calls[0];
  
  // 校验所有预期字段的规则(支持匹配器)
  expect(callArg).toEqual(expect.objectContaining({
    hello: expect.stringContaining("world"),
    foo: "bar"
  }));
  
  // 严格校验键的数量和名称,确保没有多余或缺失的键
  expect(Object.keys(callArg)).toEqual(["hello", "foo"]);
});

方法二:结合toStrictEqual与匹配器

如果不需要灵活的匹配器,直接用toStrictEqual就能完全匹配对象的结构和值:

it('should work', () => {
  const spy = jest.fn();
  const obj = {
    hello: "world",
    foo: "bar",
  }

  spy(obj);

  expect(spy).toBeCalledWith(expect.toStrictEqual({
    hello: "world",
    foo: "bar"
  }));
});

如果需要在严格匹配中使用匹配器,可以用expect.any()或自定义匹配器配合toStrictEqual:

it('should work', () => {
  const spy = jest.fn();
  const obj = {
    hello: "world",
    foo: "bar",
  }

  spy(obj);

  expect(spy).toBeCalledWith(expect.toStrictEqual({
    hello: expect.stringContaining("world"),
    foo: expect.any(String)
  }));
});

注意:toStrictEqual会严格校验对象的结构,包括键的顺序、原型链以及是否有额外属性,完全符合严格校验的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 11:40:30