Definite

Expertise

Unit Testing for Javascript with QUnit

WRITTEN BY Nurimansyah Rifwan on 04 November 2016

Introduction

Hello guys, this is my first article to learn and share how we do unit-testing for better scripting with javascript. I wrote this article hoping that we all can make a great project and minifying the effort from bug and error in the future.

Ok, so lets start learning this thing :D

First of all, i wanna introduce little bit about unit-testing. Unit-testing itself is a methodology for developer to test each functions they will create for expecting the output for each needs. As we seen, nowadays many developer don’t care about this, especially the newbie programmer. So, many developer will do the repeated task to check the bug/error for the project they built. It takes many time and price consume.

So, this methodology came out. With Unit Testing, we “developer” can create the expected result before going to write actual functional code first. From there, then we could test what a best practice for our code should be. So, we write our code and done doing stuff if the code are passed the tests.

For example, if i’m gonna create some functional script to write “Hello World” to the console/output, then i was have many expectation. Like, what if the result is not “Hello World” string or else? So, before i’m creating the function, i will write the test code first. And then, I’m going to continue write the function and test each unit/code-line with my test file. And if there is an error, i can fix them immediately without waiting the function can be used in the project/program that i’ll be built with. After that, when my code inside the function has passed out the test, then my function will work 99% out of bugs/error. (The limitation of expected result is decided first from the developer, which is “me”).

From that example, we can do much better, greater and fully controlled script on our project. That is what “Unit Testing” look a like.

The Language

There are many programming language that can adapt and use the “Unit Testing” methodology, but for my learning and tutorial, I’ll using Javascript as my main language (which is i’m using it since i’m a frontend developer) and use other related tools for learn this methodology.

QUnit: Javascript Unit Testing from jQuery

Anddd, the tools I’ll be using for this tutorial is “QUnit” from the creator of jQuery. I can’t describe it completely, but you can read the official documentation here.

Installation

For installation, we can download the library and use it directly, or we can use package management like NPM or Bower. For this tutorial, I’ll be using the downloaded one from it’s official site.

Follow the step below to learn using it with my case study:

  • Download the 2 file from the official site, which is:
  • After that, we create the development folder, for example I’m creating this folder in my web root directory:
  • Next, we place the QUnit files in the project root:
  • And I use jQuery for the DOM manipulation framework. I’m using jQuery CDN.
  • Finally we create new “index.html” as our spec-runner (The test template/layout):
    <!DOCTYPE html>
    <html>
    <head>
    	<meta charset="utf-8">
    	<meta name="viewport" content="width=device-width">
    	<title>QUnit Testing: Hello World Tutorial</title>
    	<link rel="stylesheet" type="text/css" href="qunit-2.0.1.css">
    </head>
    <body>
    
    	<div id="qunit"></div>
    	<div id="qunit-fixture"></div>
    	<script type="text/javascript" src="qunit-2.0.1.js"></script>
    	<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    
    	<!-- Our Actual Script -->
    
    	<!-- Out Test Script -->
    
    </body>
    </html>
  • Save it and we ready to go.

Case Study

Before I begin, I have a case that is used for this tutorial. The case study is about how we have some functions that will managing the words. The function will do:

  • sayHello:
    • This function must have 1 parameter for binding to the element for rendering the string.
    • This function can have optional parameter for customizing the result string. For example if I input the following “Hello Bro” string, then the expected result will be the same of what i’ve inputted.
    • If the optional parameter is empty, then it will display the “Hello World” string to the element.
    • If no parameter inputted, then it will return a false boolean.

From this example case study, we can make a test first before we write the function. Let’s get started!

Tutorial

For the story assumed before, I’ll create a “tutorial_test.js” in the “test” directory. It’s a good practice if we include the suffix “_text” for structuring our test directory. Okay, let’s write this for “tutorial_test.js“:

( function() {
	'use strict';

	// We define a module named "Tutorial".
	QUnit.module( 'Tutorial Module', function() {

		// Then we set the test
		QUnit.test( 'sayHello Test', function( assert ) {

			//-- 1. If no parameter passed, then it will return false.
			assert.notOk( sayHello(), "No parameter passed, it return false." );
			//- 2. If I pass the "#result" selector, then it will return "Hello World".
			assert.equal( sayHello( "#result" ), "Hello World", "I'm passing \"#result\" for first parameter, then it must return the \"Hello World\" string." );
			//- 3. If the optional parameter i'm passing "Hello Bro", then it will return "Hello Bro". Don't forger to set the first parameter.
			assert.equal( sayHello( "#result", "Hello Bro" ), "Hello Bro", "I'm passing \"#result\" for first parameter and \"Hello Bro\" as second parameter, then it must return the \"Hello Bro\" string when passed the optional parameter." );
		} );

	} );
} )();

 

And then we update our “index.html” file, and include the “test/tutorial_test.js” in the place reserved. Finally, let’s we do the unit test by running our server and see in the browser what it’s look a like.

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width">
	<title>QUnit Testing: Hello World Tutorial</title>
	<link rel="stylesheet" type="text/css" href="qunit-2.0.1.css">
</head>
<body>

	<div id="qunit"></div>
	<div id="qunit-fixture"></div>
	<script type="text/javascript" src="qunit-2.0.1.js"></script>
	<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>

	<!-- Our Actual Script -->

	<!-- Out Test Script -->
	<script type="text/javascript" src="test/tutorial_test.js"></script>

</body>
</html>

Normally, at the first time, you’ll get this message:

It’s because we don’t have any method named “sayHello” and yet, we haven’t create the actual javascript file. For that, let’s create a javascript file in the “src” directory. (src/sayHello.js)

// We define a function named "sayHello"
function sayHello( element ) {};

Then, we update our “index.html” again. We include the actual script file now:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width">
	<title>QUnit Testing: Hello World Tutorial</title>
	<link rel="stylesheet" type="text/css" href="qunit-2.0.1.css">
</head>
<body>

	<div id="qunit"></div>
	<div id="qunit-fixture"></div>
	<script type="text/javascript" src="qunit-2.0.1.js"></script>
	<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>

	<!-- Our Actual Script -->
	<script type="text/javascript" src="src/sayHello.js"></script>

	<!-- Out Test Script -->
	<script type="text/javascript" src="test/tutorial_test.js"></script>

</body>
</html>

After that, we re-run again. And what happens?

From 3 assertion test, 1 has passed! Hooray! Because it’s only just a simple return nothing or false.

And, what about the 2 last assertion? Let’s code our actual script. Look back our “src/sayHello.js“, then add this code:

// We define a function named "sayHello"
function sayHello( element ) {

	// Init var
	var text = "Hello World";

	// If first parameter passed, then it must return Hello World
	if ( element ) return text;

	return false;
};

And re-run the test, and….

Voila! We has passed the second test. And finally, for the last test, we could do this (back to your src/sayHello.js file):

// We define a function named "sayHello"
function sayHello( element, text ) {

	// Init var
	var text = text || "Hello World";

	// If first parameter passed, then it must return Hello World
	if ( element ) return text;

	return false;
};

Finally, re-run again, and…..

Horayy!!! Our sayHello.js script has passed the test. We finally can deploy it safely to production.

That’s it how Unit Testing works. This is just simple example. But you can try to expanding them and increasing your experience by using any different testing tools. For example, for the javascript unit-testing, beside this QUnit, you can try JasmineJS, MochaJS or whatever you like it.

For me, i’m prefer using QUnit because it developed by jQuery team and I love it rendered layout.

Okay, this is my first article and tutorial. I’ll try to do my best to make a better tutorial.

CONTACT US

HI THERE, LET'S TALK!

Mail us at contact@definite.co.id or drop us your info and let us reach out to you.



JAKARTA
Jl. Senayan No. 67
Blok S, Kebayoran Baru, Jakarta Selatan 12180, Indonesia
+62 21 739 6426
Get directions
Jl. AB I No. 16, Kavling Polri,
Ragunan, Pasar Minggu, Jakarta Selatan Indonesia
+62 21 2200 1842
Get directions
YOGYAKARTA
Jl. C Simanjuntak No. 62
Gondokusuman DI Yogyakarta 55223, Indonesia
+62 21 739 6426
Get directions