DEV Community

Cover image for Javascript: Unit Testing using Jest
Pau Riosa
Pau Riosa

Posted on

Javascript: Unit Testing using Jest

Install Jest

$ yarn add --dev jest
Enter fullscreen mode Exit fullscreen mode

or

$ npm install --save-dev jest
Enter fullscreen mode Exit fullscreen mode

Setup

In this example, we are going to create a sample function that prints "Hello world" and test it using jest in javascipt.

For us to begin, we need to create a folder in our directory, and create a three different files namely
hello_world.js, hello_world.test.js and jest.config.js

$ mkdir hello_world 
Enter fullscreen mode Exit fullscreen mode
$ touch hello_world/hello_world.js
Enter fullscreen mode Exit fullscreen mode
$ touch hello_world/hello_world.test.js
Enter fullscreen mode Exit fullscreen mode
$ touch hello_world/jest.config.js
Enter fullscreen mode Exit fullscreen mode

You should have something like this, then you are good to go.

Figure 1 Files to be included

Grind time

Now that we have setup our test environment we are going to start our unit testing using jest!

On hello_world.js, we are going to put...

function hello_world() {
  return "Hello world!"
}

module.exports = hello_world
Enter fullscreen mode Exit fullscreen mode

in hello_world.test.js

const hello_world = require('./hello_world')
test("function hello_world", () => {

  expect(hello_world()).toBe("Hello world!")
})
Enter fullscreen mode Exit fullscreen mode

in your terminal

$ jest
Enter fullscreen mode Exit fullscreen mode

Figure 2 Result

Conclusion

Just another day of learning, I am proud that I am able to manage to come up with a unit test using jest for javascript.
I am amazed for what it can do and a little bit what it can't.

Unit testing is essentially if you want to test the every functions or methods that you have in your code. This will help you simulate different scenarios, and to minimize bugs eventually.

Top comments (0)