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

Sefat Anam
2 min readMar 6, 2022

--

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.

  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 simplest way through this step. go go the existing terminal and type npm install --save-dev jest.

Step 3 : Configuration for running test

"scripts": { "test": "node ./node_modules/jest/bin/jest.js --watchAll" }, "jest": { "testEnvironment": "node" },

That’s all for now.

Step 4 : writing function & test it

For example,

scripts.js function sum(a, b) { return (a + b); } module.exports = sum;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); })

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

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

Originally published at https://dev.to on March 6, 2022.

--

--

Sefat Anam

Outside of work, I love building useful projects with TypeScript and Go.