How to add unit test cases to your project using Jest?

How to add unit test cases to your project using Jest?

Play this article

Test cases are important for any application they make the web app more efficient and most importantly all the edge cases will be covered in these test cases. Now that we are talking about testing let's talk about a testing framework called JEST for Javascript.

There are some other really great frameworks out there, and choosing one comes down to flavor and needs.

For this article, I'll use a simple JavaScript project as our basis. It will have a determination script to determine if certain statements are true or false.

Check any function

You can see the determine.js function in the main folder. This is basically our app. It's used to determine if a variable is a number.

In the most basic case, it should perform the following tests:

// Should be true

// Should be false

We first have to add Jest to our project to make this testable.

npm install -D jest

This will install the Jest package in our dev dependenies. Now we should modify our package.json to include a testing command.

"scripts": {
    "test": "jest"

The cool thing about Jest is that it can fire automatically on any files it deems testable.

By default, it can run on the following files:

  • .js files inside tests folders
  • .test.js files inside your project
  • .spec.js files inside your project

For now, let's add a determine.test.js file. This makes sense as we have our determine.js file as our basis.

To start the file, we have to import our function first.

const { isNumber } = require('./determine');

Then we can define tests. Each test is an isolated scope that can pass or fail.

Let's start by adding a test made to expect the right answer.

test('Validate a number', () => {

We start by defining the test, which holds a string (the name of the test) and executes a function. The actual test states:

Expect -> function (variables) -> to be true

I really love how Jest made these super human-readable and understandable.

We ask for the function isNumber to be true when we pass the number one to it.

We can now run the test by invoking the following command:

npm run test

image.png Image description

Wow, the test is succeeding. Now lets add a failing test case.

test('Invalidate a string', () => {

We use the same test but pass a wrong number, so the test should fail.


And it does fail, which is expected! So let's modify the test case to evaluate a false value.

#Conclusion Although this is a very straightforward test, it can be super important for example in any given number form field you need a numerical value and not any string. You can use this test case there. Moreover its in your hand how to make test cases more complicated.

##Thank You