Difference between enzyme, ReactTestUtils and react-testing-library

后端 未结 2 392
渐次进展
渐次进展 2021-01-30 06:57

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

The ReactTestUtils documentation says:

ReactTes

相关标签:
2条回答
  • 2021-01-30 07:04

    Enzyme is intended for unit/integration testing. Its API was designed to test the implementation. It offers custom renderer that doesn't require DOM (for shallow rendering), behaves differently from React renderer and allows things that are important for unit testing but aren't possible or straightforward with default renderer, like synchronous state updates, shallow rendering, disabling lifecycle methods, etc.

    react-testing-library is intended for blackbox integration/e2e tests. It uses React renderer and ReactTestUtils internally, requires real DOM because it's component's output that is asserted in tests, not internals. It doesn't provide facilities for isolated unit tests but it's possible to do this by mocking modules that contain component that need to be spied, mocked or stubbed by other means, notably jest.mock.

    react-dom/test-utils and react-test-renderer contain a subset of functionality, Enzyme and react-testing-library were built upon them. API is scarce and requires to write boilerplate code or custom utility functions for full-grown testing. React officially promotes Enzyme and react-testing-library as better alternatives.

    0 讨论(0)
  • 2021-01-30 07:24

    ReactTestUtils gives you the bare minimum to test a React component. I haven't seen it being used for big applications.

    Enzyme and react-testing-library are both good libraries that give you all the tools you need to test your application. They have two different philosophies though.

    Enzyme allows you to access the internal workings of your components. You can read and set the state, and you can mock children to make tests run faster.

    On the other hand, react-testing-library doesn't give you any access to the implementation details. It renders the components and provides utility methods to interact with them. The idea is that you should communicate with your application in the same way a user would. So rather than set the state of a component you reproduce the actions a user would do to reach that state.

    In my experience Enzyme is easier to grasp but in the long run, it's harder to maintain. react-testing-library forces you to write tests that are a bit more complex on average but it rewards you with higher confidence in your code.

    0 讨论(0)
提交回复
热议问题