Learn about testing with Jest

Tram Ho

Every project when you do, the test writing is rarely paid much attention. Most projects that customers require to write test then have the opportunity to learn more about it. So the concept of writing tests is quite vague for newcomers. Fortunately, when I was working on a project to learn about Jest. And this article will let you understand how to write test it is like?

You might think that Jest is only tested when working with React, it’s completely wrong. You can use Jest in Javascript Applications

First you need to understand, why do we need to test? Many times you write a function and we think the cases are right, but we forget about the exceptions, making the result not as expected.

Install Jest into your project using npm

Then you need to add the following line to the package.json file in the scripts

--watchAll lets you run the test again whenever there are changes in your test file

Create App.js file and export a function

Create another file, App.test.js, you can create this file in the same directory as the App.js file. Jest will automatically interpret that as a test file if you .test while naming the file

Unit test

As you independently test a small part of the project (Function / Component). For example, we add an add() function in the App.js file. Testing a function may be called unit testing

As you can see after importing the add function, we have written the test() function with the first parameter being the test title, the second parameter is a callback function, here expect(add(2, 2)).toBe(4) simply means we are expecting the add function to return 4 if we pass 2, 2

Open a terminal and type the command npm run test , You should see it

The image above shows the add function that has passed all cases

Now, let’s try it and fail like. Please change + in the add function

The test failed because it wanted 4 but actually the function returned 2

.toBe() in Jest is called a matcher. An opposite matcher with .toBe() is .not.toBe()

It will check if the result of add(10, 5) not equal to 10

You can refer to some other matcher at: https://jestjs.io/docs/en/expect

Integration Test

If a function is not passed to a test, the rest of the function that is dependent on another function fails

For example, adding and exporting a total function is connected to the add function

Run the test you will see

You can see the add and total passes the test. Now try to make a small change in the App.js file

Run the test

All our tests will fail. This is called the Integration Test

There are many concepts that I cannot say in this article. If you are interested, you can find out more on the Jest’s homepage with the link below.

https://jestjs.io/docs/en/getting-started

Share the news now

Source : Viblo