DEV Community

Cover image for Startup guide of Jest for testing your javascript code. (Beginner)
Sefat Anam
Sefat Anam

Posted on • Edited on

Startup guide of Jest for testing your javascript code. (Beginner)

The purpose of writing this article is to clarify that when a newbie learns javascript he goes through many concepts. But he doesn't know how to test code or doesn't have any idea about code testing. Today, I will make you understand how you can start learning javascript as well as writing test code also. So that, from the start phase you are confident about your code.

Today's Topics

  1. create package.json
  2. intalling jest via npm
  3. configuration for running test
  4. write function & test it.

Don't be panic, this article is very practical.

Step 1 : Create package.json

What is package.json ?
Metadata that is specific to the project. It contains a collection of any given project's dependencies. A web application is used to identify the project and acts as a baseline for users and contributors to get information about the project

To create a package.json you must have to install nodejs on your machine that's all. If you don't have nodejs installed go to this website and install it. Then open an empty folder in vs code, open terminal type npm init -y. After executing this command you can see a file is created named package.json. 😀 Dig more into understanding package.json click here

Step 2 : Install jest via npm

This is the simpliest way through this step. go go the existing terminal and type npm install --save-dev jest.

Step 3 : Configuration for running test

  • update your package.json's scripts section like this,
 "scripts": {
       "test":"npx jest --watchAll"
  },
  "jest": {
    "testEnvironment": "node"
  },
Enter fullscreen mode Exit fullscreen mode

Image description

That's all for now.

Step 4 : writing function & test it

  • Make a file like script.js
  • Also make a file script.test.js

For example,

scripts.js

function sum(a, b)
{
    return (a + b);
}

module.exports = sum;
Enter fullscreen mode Exit fullscreen mode
script.test.js

const sum = require('../script')


test('Sum of (1,1) = 2', () =>
{
    expect(sum(1, 1)).toBe(2);
})
test('Sum of (2,3) = 5', () =>
{
    expect(sum(2, 3)).toBe(5);
})

test('Sum of (3,7) = 10', () =>
{
    expect(sum(3, 7)).toBe(10);
})

Enter fullscreen mode Exit fullscreen mode

After writing your function & tests code. Go to terminal and run npm run test. You can watch something like this ,

Image description

Cool 😎 huh !
Yes, now you got the point that I want to share with you.
From today try to build up writing tests for your code & understand your code better. 💖

Signing off.
Sefat

Top comments (1)

Collapse
 
sefatanam profile image
Sefat Anam

test command should be this "test":"npx jest --watchAll"