Day 91 - Javascript Unit Testing With JEST.js

I tried to do some open-source coding which I have never done before and was looking for a project to contribute to can came upon one which wanted new user to write tests for the code. So I thought this was the right moment to learn about some unit testing in JS.

Unit Testing

Unit Testing is a method to test the written code to check if it is fit for use and does what it is intended to do. There are two ways to do unit testing, Manual or Automatic.

  • Manual. where programmers or some other person checks the code one by one to check it works correctly.
  • Automatic. where programmers write code that do the testing for them.

Manual testing is a lot of work and prone to error so mostly we do automaice code based testing.

JS Code Testing

The project i was trying to contribute to wanted beginners to write test for TypeScript (A Superset of JavaScript), which is same as JS with some extras. To do testing for JS code there is a framework called JEST.js which was developed by Facebook to test React code but now can be used to test both forntend and backend JS.

JEST.js

JEST is a framerwork for JS unit testing by Facebook. It can be used to test both backend and frontend JavaScript code. To use it we first have to install in our project as a DevDependency.

npm install --dev jest

Add following to scripts in package.json file in the projecst directory.

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

We then create a file and write some code to test.

// add.js
function(a, b) {
    return a + b
}

We then create a file which ends with .test.js instead of .js which lets the jest to pick it up automatically to test.

// add.test.js
const add = require("./add");

test("1 + 2 is equal to 3", () => {
  expect(add(1, 2)).toBe(3);
});

We run the following command in the terminal and it will test it for us and prints the result in the terminal.

User@Linux>> npm run test

PASS  ./sum.test.js
✓ adds 1 + 2 to equal 3 (5ms)

This was a simple way to show how JEST works. To learn more about it check out the Documentaion for complete info about what more JEST can do.


zainscizainsci