gpt4 book ai didi

testing - Jest 中的 'toBe' 和 'toEqual' 有什么区别?

转载 作者:行者123 更新时间:2023-11-28 19:39:06 26 4
gpt4 key购买 nike

Jest 文档如下:

toBe just checks that a value is what you expect. It uses === to check strict equality.

对于toEqual:

Use .toEqual when you want to check that two objects have the same value. This matcher recursively checks the equality of all fields, rather than checking for object identity—this is also known as "deep equal". For example, toEqual and toBe behave differently in this test suite, so all the tests pass.

const x = { a: { b: 3 } };
const y = { a: { b: 3 } };

expect(x).toEqual(y);
expect(x).toBe(y);

在这种情况下,toEqual 通过但 toBe 失败。我知道 toEqual 通过是因为它进行了深度相等 检查。为什么 toBe 在这种情况下会失败?

此外,是否有使用 toBetoEqual 的最佳实践(不仅在 Jest 中,而且在其他测试框架中也是如此)?

最佳答案

它失败是因为 xy 是不同的实例并且不等于 (x === y) === false。您可以将 toBe 用于字符串、数字或 bool 值等原语,而对于其他一切使用 toEqual。例如

x = 4 
y = 4
x === y // true

x = 'someString'
y = 'someString'
x === y // true

空对象也不相等

x = {}
y = {}
x === y //false

关于testing - Jest 中的 'toBe' 和 'toEqual' 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45195025/

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