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

标签 testing jestjs

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/

相关文章:

testing - 如何授予客户端访问预览 Web 应用程序的权限

Angular (4.0.0-beta.8) 测试组件夹具在使用子组件执行测试后未定义

javascript - 无法多次模拟函数 react 、测试

node.js - 用 Jest 重置单个模块

react-native - react 原生静态图像的 Jest 快照抛出警告

javascript - 方法在单元测试中不可用

google-chrome - 如何在 Selenium 中设置 Chrome 的窗口大小?

testing - DoThrow MailException 与 mockito

java - 使用 JUnit 测试 JavaFX 应用程序

vue.js - 使用 jest 和 vue-test-utils 进行 Vue 测试无法解析通过 app.component() 引入的组件