【问题标题】:Empty object matches object with different properties on toMatchObject in Jest空对象匹配 Jest 中 toMatchObject 上具有不同属性的对象
【发布时间】:2022-08-18 21:53:06
【问题描述】:

在使用空对象测试具有属性的对象时,我的测试通行证:

it(\'Should not match object with properties with empty object\', () => {
  const testingObject = { a: 1, b: 2 };

  expect(testingObject).toMatchObject({});
});

现在,当与具有不属于testingObject 我的测试的另一个属性的对象进行比较时通行证,这是预期的:

it(\'Should not match object with property that does not exist in the original object\', () => {
  const testingObject = { a: 1, b: 2 };

  expect(testingObject).not.toMatchObject({ c: 3 });
});

这种行为很奇怪,因为我预计这两个测试都会失败。

    标签: testing jestjs match


    【解决方案1】:

    事实证明,这是Jest Github issue 的预期行为。

    还有一位贡献者添加了explanation:

    像 {hello: 'hello'} 这样的非空接收对象确实匹配空的预期对象

    接收到的空对象与 {hello: 'hello'} 等非空预期对象不匹配

    也就是说,接收的值必须具有所有预期的属性,但可以具有其他属性。

    这意味着我们应该期望这种情况发生,因为预期的空对象至少是与接收对象相同的对象,但不能具有不属于接收对象的属性。

    我们可以进行此比较的唯一方法是:

    it('Should not match object with properties with empty object', () => {
      const testingObject = { a: 1, b: 2 };
    
      expect(testingObject.a).not.toBeUndefined();
      expect(testingObject.b).not.toBeUndefined();
    });
    

    【讨论】:

      猜你喜欢
      • 2019-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-14
      • 1970-01-01
      相关资源
      最近更新 更多