Let’s TEST your JavaScript Code

Well, Writing a test case is something that most developers would neglect to do. But this is also the most important part in the software project life cycle. So here in this article I share my experience on how to test your JavaScript code.

let’s take a very simple function where is add two given numbers.

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

If we wanna write a test for this function we can actually write our own code using IF ELSE

if( sum(1,2) == 3 ) {
console.log('Test Pass')
} else {
console.log('Test Fail')
}

But this is a bit overhead when it comes to bugger code. To make the things cleaner we can use a test library.

Let’s use JEST.

Jest is a JavaScript testing framework designed to ensure correctness of any JavaScript codebase.

01. Setup package.json to the project

npm init -y

02. Install Jest as development dependency

npm install --save-dev jest

Now we can use jest to test our JavaScript code. let’s take the same example we used above. the sum.js.

03. Create the test file

Create a file with the same name of the file to be tested like bellow.

sum.test.js

04. Import the function to be tested into the test file

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

05. Write the test description for the test.

test("properly adds two numbers", () => {
// test should come here
});

test function need two parameters. first one is the description about the text and that is just a string value, second one is the callback function to do the actual test.

06. Write the test using jest matchers

expect(sum(1, 2)).toBe(3);

There are many matchers that can be used for your purpose, and those can be seen in this document.

Anyway, final text file can be seen like this.

07. Change the package. json file scripts to run the tests

"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},

Change the above to

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

Now, you can simply run npm test in the command line.

If you want to see more information about the test, we can add an option to package.json command for test like this.

"scripts": {
"test": "jest --coverage"
}

This will give you a full coverage about the test in the command line, plus this will also generate a some files in the folder with a html page to see the coverage nicely.

Here is the command line output.

Here is the new folder create for the coverage.

When you open the index.html inside Icov-report folder

That’s all folks.

I hope as a developer we should all write some unit tests to ensure the work we do. That should definitely make you special with other developers. Also it is a very good practice to pass the tests before going production.

So, I really encourage you to write some unit tests for your code.

Cheers !!!!

Senior Software Engineer ❤️ Node | Ruby