gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 03:15:51 27 4
gpt4 key购买 nike

我写了下面的测试:

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

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

最佳答案

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

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

  • .toMatchObject() 仍然会通过,as seen in the docs .

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

关于javascript - '.toMatchObject' 和 'objectContaining' 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45692456/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com