2019-08-10
1. Can we use Jest or Enzyme?
Hooks can only be called inside the body of a function component
. (https://fb.me/react-invalid-hook-call)
The error above means that Hooks are not yet supported in Enzyme as seen in this issue here.
As a result, we cannot use Enzyme to carry out component tests for React Hooks. So what can be used?
2. Introducing react-testing-library
react-testing-library is a very light-weight solution for testing React components. It extends upon react-dom and react-dom/test-utils to provide light utility functions. It encourages you to write tests that closely resemble how your react components are used.
3. Installation
This module is distributed via npm
which is bundled with node
and should be installed as one of your project’s devDependencies:
1 | npm install --save-dev @testing-library/react |
This library has peerDependencies
listings for react
and react-dom
.
4. Suppressing unnecessary warnings on React DOM 16.8
There is a known compatibility issue with React DOM 16.8 where you will see the following warning:
1 | Warning: An update to ComponentName inside a test was not wrapped in act(...). |
If you cannot upgrade to React DOM 16.9, you may suppress the warnings by adding the following snippet to your test configuration learn more
1 | // this is just a little hack to silence a warning that we'll get until we |
4. configuring some import
1 | import '@testing-library/react/cleanup-after-each' // deprecated |
these imports are something you’d normally configure Jest to import for you.
automatically. Learn more in the setup docs: https://testing-library.com/docs/react-testing-library/setup#cleanup
sample test Header
1 | import * as React from "react"; |