I was recently continuing to develop the Kindle UI library and thought it was time to write some tests, so I decided to use the Mocha testing scheme (to try something new).
(This paragraph is generated by GPT 👉) During the development process, it is very important to ensure the accuracy Testing is one of the effective ways to achieve this, especially in JavaScript development. In React application development, Mocha and Chai are two very popular testing frameworks. This article explains how to use Mocha and Chai to test React applications.
Why not use the official Jest tests recommended by react?
Jest was originally designed for testing react apps. Compared to Jest, Mocha is more flexible (the latter can and must be additionally configured, while the former works out of the box), runs in both browser and node environments, and supports complex statements such as
Since my project is not a single react app but a monorepo, using mocha in the workspace root is definitely a better choice.
Mocha itself does not support JSX, so we need to install a few dependencies.
Note: If you are installing test dependencies in the workspace root (the recommended practice), remember to add the -W parameter.
Configuring Mocha
Create a file in the project root directory with the following contents.
Create a file in the directory
Configuring Babel
With babel, we can use test files in cjs format without the annoying setting.
Testing
Add a shortcut script to , here please configure it according to the actual project.
After that we can happily write tests.
For more information about the usage of react-test-renderer, you can refer to the official documentation.
Some common testing scenarios are listed here for reference.
Check component type
Check rendering result
Improvements
The official testing library provided by react is rather limited, for example, we can't test whether an element is visible or not, and we can't simulate a user operating the page.
So, we can use to improve it further.
Note that there is no document object in the node environment, so we need to simulate one using the JSDom library.
Start by adding hooks to mocha.
Update your test code:
You can explore further such as using User Event. Happy testing! ♥