Jest – how works and why we need it?

Hi, in this post we are going to talk about how Jest works and why we need it.

So, let me clarify that React Testing Library (RTL) help us with rendering components into virtual DOM (with the render method), help searching virtual DOM and also interacting with the virtual DOM.

However RTL needs a test runner: to find test, run them and make assertions that’s where Jest comes in. There’s other libraries that help with this like: Mocha, Jasmine. But Jest is recommended by RTL and also comes whit the “create-react-app”.

When we run this command:

npm test

Runs an npm script that runs Jest in watch mode.

What is a watch mode?

Is a way that we can run Jest, so that will watch for any changes in files since the last commit, only run tests related to these files that changes since the last commit.

And if we change something in our files then the terminal will do the same process, because is watching for changes.

So, I’m going to commit a change:

Then I’m going to run “npm test” again:

And now we can see in terminal how a text message say:

“No tests found related to files changed since last commit.”

So the watch mode (npm test) is a way that we can run Jest, so that will watch for any changes in files since the last commit.

How does Jest work?

There is a global method called “test” that has 2 arguments: the first argument is the string description that let us know which test fail and the second argument is the test function and Jest run that function to determine if our test success or fail.

Our test fails if error is thrown when running the test function, the assertions throw errors when our expectations fails, so if there is not error in the test function then the “test pass” also an empty test pass.

By Cristina Rojas.