73

What is the difference between enzyme, ReactTestUtils and react-testing-library for react testing?

The ReactTestUtils documentation says:

ReactTestUtils makes it easy to test React components in the testing framework of your choice.

The enzyme documentation just says:

Enzyme is a JavaScript Testing utility for React that makes it easier to assert, manipulate, and traverse your React Components' output.

React-testing-library documentation:

The react-testing-library is a very light-weight solution for testing React components. It provides light utility functions on top of react-dom.

Why is actually every solution easier and what can't be achieved with the other one?

4

3 回答 3

138

ReactTestUtils 为您提供了测试 React 组件的最低要求。我还没有看到它被用于大型应用程序。

Enzyme 和 react-testing-library 都是很好的库,可以为您提供测试应用程序所需的所有工具。虽然他们有两种不同的哲学。

Enzyme 允许您访问组件的内部工作。您可以读取和设置状态,还可以模拟孩子以使测试运行得更快。

另一方面,react-testing-library 不会让您访问实现细节。它呈现组件并提供与它们交互的实用方法。这个想法是您应该以与用户相同的方式与您的应用程序进行通信。因此,与其设置组件的状态,不如重现用户为达到该状态而执行的操作。

根据我的经验,酶更容易掌握,但从长远来看,它更难维护。react-testing-library 强制您编写平均而言更复杂的测试,但它会奖励您对代码的更高信心。

于 2019-01-11T19:28:38.937 回答
62

Enzyme用于单元/集成测试。它的 API 旨在测试实现。它提供了不需要 DOM(用于浅层渲染)的自定义渲染器,其行为与 React 渲染器不同,并允许对单元测试很重要但使用默认渲染器不可能或直接的事情,例如同步状态更新、浅层渲染、禁用生命周期方法等

react-testing-library用于黑盒集成/e2e 测试。它在内部使用 React 渲染器和 ReactTestUtils,需要真正的 DOM,因为它是在测试中断言的组件输出,而不是内部。它不提供用于隔离单元测试的工具,但可以通过模拟包含需要通过其他方式(尤其是jest.mock.

react-dom/test-utilsreact-test-renderer包含功能的子集,Enzyme 和 react-testing-library 是在它们之上构建的。API 稀缺,需要编写样板代码或自定义实用程序函数以进行全面测试。React正式推广Enzyme 和 react-testing-library 作为更好的选择。

于 2019-01-11T19:38:50.777 回答
2

React 测试库可以替代 Enzyme。它们有非常不同的测试理念——Enzyme 鼓励(并提供实用程序)使用渲染的组件实例测试实现细节,而 RTL 鼓励通过查询和断言实际 DOM 节点来仅测试“最终结果”。

于 2021-09-02T21:22:30.270 回答