Author | sanjeev sharma
Translator |Xu Xuewen.
Curated |Ding Xiaoyun.
Are you planning to write tests for your React?Feeling frustrated that you can't find a good tutorial to get started?Well, this article is exactly what you need. In this article, we'll cover all the steps to write unit tests and the bugs and issues you may encounter along the way.
This article uses the JEST and React Testing Library libraries. It's okay if you want to use other libraries, some of the basics in this article will also help.
All of the ** covered in this article is hosted on GitHub, and links are provided at the end of this article.
Of course, product development can be done without writing tests. Users, product managers, and even testers or QAs don't care if the product is tested**. But you, as a developer, should care!
Let's say you have a user with tens of thousands of users, and when you do some refactoring (or add a feature fix) to a public utility function, and you test it somewhere in your app where it is called, it shows that the function works. So you choose to go live on Friday (which is a low-level bug). The function then fails to work elsewhere in the app, causing an online outage during the weekend. At this point, how you wish there were tests in these places that could be run automatically before the release to production, thus avoiding this failure.
The above scenario is more common than you might think. You probably haven't encountered it yet (it's a matter of time, though), but a lot of engineers, including me, have already encountered it.
Therefore, testing is important for several reasons:
Boost your confidence in the launch of the launch.
A test is a document in its own right.
Useful for debugging and refactoring.
In the long run, it helps to reduce development time.
For all junior developers looking to move up the ranks, it's important to have the ability to write tests.
We'll teach you how to write tests from scratch**, so have your terminal ready. First, let's create a sample project using Vite.
After you create your project, run it with the following command.
Once the program is running, you'll see a demo app on the page.
We won't be adding new features to the app, but in order to write tests for the buttons, we need to refactor the buttons into a separate component.
Next, let's add two buttons to the page:
The function of a button is to multiply the value of count by 2 when clicked. Another button does the following thing when clicked: if the value of count ends in 0, divide its value by 2. If the value of count is a Fibonacci number, then add its value by 1. Otherwise, square the value of count.
We need to declare the two functions used above in the utils module. At the same time, we also declare some helper functions, but since they are not used elsewhere, we don't need to export them here.
*Ready, now it's time to start writing tests**. Here we skip React and write tests for the utility function first. This helps us understand the general usage of the Jest framework.
Next, let's write a test for the doublethenum function.
The ** above is used to test if our function executes as expected. Any test** will include these key components:
describe function: The first parameter is a string, which will be displayed when the test runs. The second parameter is to test the function that is actually executed. The main purpose of the describe function is to group tests of the same type. There's only one test here, and in the other example, you'll see that there are multiple tests. itFunction: Its argument structure is similar to that of the describe function. However, the string argument here should describe the test function in as much detail as possible. Of course, you can also use the test function instead of it. Expect Statement Block: The first three lines in this function are simple. The last line is an assertion to determine if the doublethenum function is working correctly. In addition, we use the toequal matcher function here. Jest offers a lot of matchers, such as:
tobenull is used to match null.
tobetruthy is used to match statements that have a verdict of true. For more information about the matchmaker, please refer to the following link:
In order to run the tests, we need to install jest:
Then in the packagejson:
Finally, run the test by executing the yarn test command.
For most people, the steps above are sufficient. But if you're having any issues with module imports or TypeScript, follow these steps:
Install and set @babel preset-env:
Then, configure it to the packageJosn:
Install TypeScript dependencies:
Then, in jestconfig.ts
The test is then executed, and the results are as follows:
From the output you can see the string information we declared in the describe and it functions.
Congratulations, you've completed your first test!
Like this article?If you think it's pretty good, I recommend checking out another of my most popular articles, The Complete Guide to Redux, which has been read by 250,000:Next, let's write tests for the funkynum function.
When writing tests, you should cover as many branches and statements as possible of your functions. The higher the test coverage, the more confidence a person will have.
If you run the test again, you should see the following output.
Ideally, we should also write separate blocks of describe statements for the isfibonacci and isperfectsquare functions. In unit tests, the tests should be independent of each other. For the sake of brevity, we are not doing that here.
Tips. By calling. skip or testskip to skip any tests, or call describeskip to skip the entire test block.
By calling itonly or testonly performs a single test.
We've already covered how to use Jest for JS testing. Now, let's dive into the tests on React.
Before we get started, we also need to install some dependency libraries:
At the same time, you also need to set up a game in jestconfig.TS:
Let's write a basic test for the counterbutton component:
In the above section, we provided the required props and tried to render the component. For any component, this should be the first test you write for it. Because if that test fails, then the other tests are useless.
The render function of RTL (React Testing Library) will be set in the documentbody.
It also returns some query methods such as GetByText that can be used to find elements in the DOM.
Click here for all enquiries.
If you run the test again, you should see 2 sets of tests - all green and passing.
The second test we wrote was to test the component's response to props. If the props don't have interdependencies, then separate tests should be written for each prop parameter.
The getbytext function is a query method that allows us to get an element by a string.
The tobeinthedocument function is a matcher similar to toequal. jest does not provide this function by default, and you need to install the @testing-library jest-dom library before you can use it.
Different environments have different packages, such as in React Native, which requires the use of @testing-library jest-native.
If you run the test again, the test should pass as well.
Finally, let's write the last and most important test of this article. We'll write a test to check if the click event handler is working as expected.
In order to generate user events (e.g. clicks and keystrokes), we need to install another package.
Compared to the previous test**, this test** is almost the same, with only a few minor differences.
Note: Since it simulates a user event, this function is executed asynchronously.
jest in the first linefn() is an analog function. It allows you to track a lot of useful information such as call parameters, number of calls, and so on while the test is running. Functions like this, you'll see a lot of them later.
We've also used a new query method, getbyrole, to find button elements.
Before checking if the mock function is called, we need to wait for the click event to complete.
That's it!If you run the tests, they should pass as well.
Get all **::
If you've successfully completed the writing of your tests following this article, you can start adding tests to your library and explore the various testing features further.
In addition, I suggest you learn more about the following:
getbytestid - This is a very common query method. It can be used when other methods fail. Learn about setup and teardown methods. It will elevate your testing. Learn how to simulate npm modules, API calls, global state and context, and more. Original link: React Unit Testing Examples: A Quick Start Guide Architecture Frameworks Featured InfoQ article.