'.toMatchObject' 和 'objectContaining' 有什么区别

新手上路,请多包涵

我写了以下测试:

 it('Can decrement the current step', function () {
    expect(reducer(TestState, { type: 'GOTO_PREVIOUS_STEP' })).toMatchObject({ currentStep: 4 });
});

it('Can decrement the current step v2', function () {
    expect(reducer(TestState, { type: 'GOTO_PREVIOUS_STEP' })).toEqual(expect.objectContaining({ currentStep: 4 }));
});

两个好像都过关了,有什么区别吗?它们之间有性能影响吗?

原文由 Julito Sanchis 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 772
2 个回答

通过查看文档和我自己的实验来证实这一点,不同之处在于处理嵌套在作为期望传递的道具中的对象。

如果期望对象有一个属性,包含一个对象,该对象包含实际对象的等效属性中的 部分但不是全部 属性,则:

  • .toMatchObject() 仍然会通过, 如文档中所示

  • expect.objectContaining() 将失败(除非您在期望对象本身中使用 expect.objectContaining() 声明该属性)

示例(在 Jest 中测试):

   // objectContaining, with nested object, containing full props/values
  // PASSES
  expect({ position: { x: 0, y: 0 } }).toEqual(expect.objectContaining({
    position: {
      x: expect.any(Number),
      y: expect.any(Number)
    }
  }));

  // objectContaining, with nested object, containing partial props/values
  // FAILS
  expect({ position: { x: 0, y: 0 } }).toEqual(expect.objectContaining({
    position: {
      x: expect.any(Number)
    }
  }));

  // objectContaining, with nested object, also declared with objectContaining, containing partial props/values
  // PASSES
  expect({ position: { x: 0, y: 0 } }).toEqual(expect.objectContaining({
    position: expect.objectContaining({
      x: expect.any(Number)
    })
  }));

  // toMatchObject, with nested object, containing full props/values
  // PASSES
  expect({ position: { x: 0, y: 0 } }).toMatchObject({
    position: {
      x: expect.any(Number),
      y: expect.any(Number)
    }
  });

  // toMatchObject, with nested object, containing partial props/values
  // PASSES
  expect({ position: { x: 0, y: 0 } }).toMatchObject({
    position: {
      x: expect.any(Number)
    }
  });

原文由 Jonathan 发布,翻译遵循 CC BY-SA 4.0 许可协议

我的想法是 expect.objectContaining ( _和其他类似的匹配器_)可以用来代替传递给其他匹配器的“对象”中的文字值。

这个例子来自文档:

 test('onPress gets called with the right thing', () => {
  const onPress = jest.fn();
  simulatePresses(onPress);
  expect(onPress).toBeCalledWith(expect.objectContaining({
    x: expect.any(Number),
    y: expect.any(Number),
  }));
});

因此,虽然它们在您的示例中似乎做同样的事情,但 expect.* 在其他方面也很有用。

原文由 David 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题