Javascript Application Testing, Intro to Unit Testing using Jest 01

List Of Content

ADS Area (CARBON)

ADS Area (CARBON)

 

Getting Started

Being Able to Develop your Own application either alone or as a team isn't enough for you to create high-level apps and better user experience with fewer bugs and errors so knowing how to test your own applications is mandatory for either having a good career or the job you want or on the other hand creating smooth apps by testing them just before the release stage to make sure that everything is working as expected to be from your side.

So Testing Javascript is almost the same as testing any other application in whatever language or framework you worked with, in this case, we will use Jest Testing Utility (Which is Made by the Great Facebook Team) since it is very lightweight and offers a lot of features and helper function in a snap of a finger.

Of course, you need to know how javascript apps work and at least some basic knowledge about Node.js but still optional.

Also, you can grab the project from Github.

Our Custom Project Structure:

--dist/
--src/
----app/
------utils/ ///< Some Utils Functions (For Unit Testing)
--------index.js
--app.js
--package.json

 

First, we need to install jest on our javascript project (your application).

npm install jest --save-dev 

This is all you need to install in order to run tests you create for your specific application API.

Intro to Unit Testing 

Now, probably some of you can't quietly figure out what is Unit Testing, so let me guide you through the forest, follow me.

In the Term of Application Testing, there are three main Testing Types (Categories) Unit, Integration, and End-To-End testing each one has its own pros and cons and what scenarios to use one over the other for testing your applications and since we only gonna go through Unit testing so let's start from there.

You can take a look at the testing diagram (the higher we go on the pyramid the harder it gets to test our application).

 

 

 

 

 

 

So Unit testing is running tests for each part of your application alone dependently from the whole application logical link and working behavior, it is used to make sure dependent parts are working as expected to be, for example on our tutorial we will cover two dependent methods under the utils on for validating a URL and the other for concatenating two objects (merging) and creating new instance object, so we will test each one separately with different values to make sure it behaves as we expected it to be otherwise we have to fix that.

Where to Put Test Files 

There are specific places that by convention you should place you app test file under otherwise it would be a little bit harder either for your or for someone else trying to maintain the code you wrote so make sure to stick to the rules.

For Unit testing, the test files are usually placed under the same directory as the functions being tested (in our case we would place it in utils) but that is not all we also need to create a directory for containing the test files on that directory.

The test directory also has a naming convention as well as the test files names. so for directories, it better be named like (__tests__ or tests) and for files you need to append a test suffix (for ex: utils.test.js) to let Jest and your IDE know that this is a testing file for the application.

Testing Utils Functions

I chose utils functions to cause they are very easy to implement and understand by anyone who knows the basics of javascript and programming in general so it would look obvious after reading through lines of code very easily.

Now, as we have discussed the naming convention of testing files and directories we will create a test file for the utils module.

/*__tests__/utils.test.js*/
//Import the Functions you want to test in the test file
const utils = require("../index");

First, we will use describe function which is just responsible for organizing the tests to know which tests belongs together in order to be able to have better control over the produced fails and bugs and easily fix them.

describe("Testing Utils", () => {
  test("URL Regex Validation", () => {
    let testURL = "https://google.com";
    expect(utils.isURL(testURL)).toBeTruthy();
    expect(utils.isURL("htt:/facebook.com")).toBeTruthy();
  });

Under describe, we use the test function which basically represents a single test to run and inside the callback, we would create the test case and of course, we use the jest testing API for that.

  • expect is a function that takes a value (string. number, boolean) and gives you the ability to check against the value.
  • There are many methods to be used to checking the output or return value of your function (isURL).

We use toBeTruthy to check if the return value of isURL with testURL variable, you can use whatever method that suits your test scenario, you can check the List.

Also, in the end, we add a wrong case which is just for checking if the isURL function returns false on wrong cases.

Using the same method explained above we can now test the other function (concatObjs) which basically takes two object instances and creates a new instance and concatenates them into it.

//Inside the Same Describe function scope since it goes through the same test scope.
test("Object Concatenation", () => {
  let obj1 = { name: "alex", carrer: "web dev" };
  let obj2 = { name: "olly", age: 27 };
  //Check if it works against empty objects.
  expect(utils.contactObjs({}, {})).toEqual({});
  //Also using a valid objects
  expect(utils.contactObjs(obj1, obj2)).toHaveProperty("job");
  //using toHaveProperty and you give it the property name 
});

Running Jest Tests

For running the created tests, now we need to add a script to the package.json in order to be able to use it through npm.

/*package.json*/
{
  "name": "app-testing",
  "version": "1.0.0",
  "description": "Simple App Testing For Ipenywis Tutorials",
  "main": "app.js",
  "directories": {
    "test": "tests"
  },
  "scripts": {
    "test": "jest --watchAll"
  },
  "keywords": [
    "Jest",
    "javascript",
    "Testing"
  ],
  "author": "Islem Penywis",
  "license": "MIT",
  "devDependencies": {
    "jest": "^23.6.0"
  }
}

Make sure to add test script with jest --watchAll to run it in watch mode so whenever you do changes and save the test will re-run automatically.

Try to Run 

npm run test 

Jest will automatically look for your test files by default under the __tests__ or tests folders on your source code then runs them for you.

You should get something similar to the output above.

As you can clearly see that there are success tests and fail tests which prove to you that testing actually matters on any application whether small or big.

 

What's Next

As a practice try to run the tests by your self and fix the bugs either on the application or in the tests to see how it works behind the scenes.

Make sure to take a look at the available methods for testing for having a full look over what you can do with Jest and it's lightweight but rich testing API.

in the Next Tutorial on the series, we will dive deep into more complicated things and try to cover other test types and categories (Integration Test).

Share Tutorial

Made With By

Ipenywis Founder, Game/Web Developer, Love Play Games