Jest | Shalini Chauhan

Post

editor-img
Shalini Chauhan
Apr 20, 2023

Jest

Jest is a JavaScript Testing Framework.

Read that again! It's simply designed for JavaScript, not necessarily React!

You could use Jest to test a simple function that returned Hello World from a pure JavaScript function. Or you could use a library like we are going to with React, and test the functions that you write for the results you expect.

The key difference here is that Jest is agnostic across all JavaScript frameworks, it doesn't care if you're using Angular (but I am judging you for it), Vue, React, or just plain JavaScript.

At its core, you can just think of Jest as a pure JavaScript function runner, which:

- Takes in a function

- Runs it in an isolated environment with configuration of your choosing

- Compares the behaviour of that function with what you expect it to be.

React Testing Library

React Testing Library allows you to write code to test your React Components, and the DOM nodes within them.

This is different from Jest as it is specifically designed to run with React, and utilises the DOM Testing Library under the hood to represent React components as accurately as possible when compared to the real thing.

Okay, so why do we need both? Great question! Well, the way I like to see it is that there are two main reasons.

Jest enables us to easily run our React Testing Library tests, using the Jest Test Runner. This means we can write ___.test.js files and easily run them with the jest command on the command line.

React Testing Library enables us to query and check the DOM nodes and then use Jest's assertions to make checks on those nodes. Hopefully, you're clear on why each tool exists, and why we want to use both the tools to run tests for our Next.JS applications.