This video is available to students only

Testing useBoolean hook

First of all, we need to install all the required dependencies in package.json to test our hooks, and delete the useless index.test.ts from the root.

If you're not familiar with the @testing-library set of libraries, they are basically a set of wrappers around DOM selectors and other custom selectors that make testing more user-behavior-centric.

By "user-behavior-centric" I mean its API is designed in such a way that components are selected by user-centric terms like findByLabel or findByText rather than React.displayName or plain old CSS selector. Tests will look like a high-level user interaction scenario. These scenarios are way more important to the user, and hence the developer, than any of the implementation details, which they wouldn't be losing any sleep over.

It's about letting your tests give you the confidence that they are intended to. Since implementation details are not under test, we can easily refactor our components or even change an underlying framework without changing any of the test cases and assertions, changing only the preparation phase of the tests.

These libraries are absolute gold, and if you're still using enzyme for unit testing your React components, you would do well to change to @testing-library/react as soon as possible.

If we're testing functions (meaning unit tests rather than integration tests) we need to go down to the raw variables, reference comparisons etc. In the case of hooks testing, to avoid rendering some dummy components, we're going to use @testing-library/react-hooks package, which is essentially a set of helpers to test hooks in isolation. The authors of the library recommend, and I concur, that you should only use that for highly reusable hooks or hooks libraries such as we're writing now. In other scenarios you should test the whole component instead, using just @testing-library/react.

Okay. I think we've cleared everything up here, so let's start writing tests!

We're going to create useBoolean.test.ts file in __tests__ folder, alongside our useBoolean.ts file.

We should add a describe block, and all cases need to be checked using it blocks.

Start a new discussion. All notification go to the author.