“.toMatchObject”和“objectContaining”有什么区别

2022-08-30 05:43:00

我写了以下测试:

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 }));
});

他们俩似乎都通过了测试,他们之间有什么区别吗?它们之间是否有性能影响?


答案 1

从文档和我自己的实验来证实它,区别在于处理嵌套在作为期望传递的道具中的对象。

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

  • .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)
    }
  });

答案 2

我的想法是,(以及其他类似的匹配器)可以使用,而不是你传递给其他匹配器的“对象”中的文字值。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.*