Advertisement
JavaScript & AJAX

Quick and Easy JavaScript Testing with “Assert”

by

Years ago, I learned a deceptively simple "assert" function from John Resig, for testing your JavaScript. Amazingly, at barely five or six lines, this code provides a great level of power and control over your code, when testing. I'll show you how to use it in today's video quick tip.


Full Screencast



“Assert” Code

 
<!DOCTYPE HTML> 
<html lang="en-US"> 
<head> 
	<meta charset="UTF-8"> 
	<title>Easy JavaScript Testing </title> 
	<style> 
		.pass:before { 
			content: 'PASS: '; 
			color:  blue; 
			font-weight: bold; 
		} 
 
		.fail:before { 
			content: 'FAIL: '; 
			color: red; 
			font-weight: bold; 
 
		} 
	</style> 
</head> 
<body> 
 
<ul id="output"></ul> 
 
<script> 
var output = document.getElementById('output'); 
 
function assert( outcome, description ) { 
	var li = document.createElement('li'); 
	li.className = outcome ? 'pass' : 'fail'; 
	li.appendChild( document.createTextNode( description ) ); 
 
	output.appendChild(li); 
}; 
</script>

That’s all you need for most basic testing! The assert function accepts two parameters:

  1. outcome: A boolean, which references whether your test passed or failed
  2. description: A short description of your test.

The assert function then simply creates a list item, applies a class of either “pass” or “fail,” dependent upon whether your test returned true or false, and then appends the description to the list item. Finally, that block of coded is added to the page. It’s crazy simple, but works perfectly.


Test 1: Your First Example

 
function add(num1, num2) { 
	return num1 + num2; 
} 
 
var result = add(5, 20); 
assert( result == 24, 'Checking the add function'); 
 
// OR 
assert( add( 5, 20 ) == 24, 'Checking the add function');


Test 2: Closures

 
var someArray = [1,2,3,4,5], 
	len = someArray.length, 
	i = 0; 
 
var count = 0; 
 
for ( ; i < len; i++ ) { 
	setTimeout(function() { 
		assert( count++ === i, 'Checking the value of: ' + i ); 
	}, i * 300); 
}

Uh oh! What happened?

This is a common issue, and the answer is to implement a closure, so that we can remember the value of "i." Otherwise, as we noticed above, the code will only render the final value in the sequence: 5.

 
var someArray = [1,2,3,4,5], 
	len = someArray.length, 
	i = 0; 
 
var count = 0; 
 
for ( ; i < len; i++ ) (function(i) { 
	setTimeout(function() { 
		assert( count++ === i, 'Checking the value of: ' + i ); 
	}, i * 300); 
})(i);


Conclusion

At first, it might appear as if only huge JavaScript libraries and such require some form of testing; however, that's far from the truth. As we've demonstrated, even a simple function, like Resig's "assert", can potentially save us from hours of debugging! So what do you personally use to test your code?

Related Posts
  • Code
    HTML5
    HTML5: Battery Status APIPdl54 preview image@2x
    The number of people browsing the web using mobile devices grows every day. It's therefore important to optimize websites and web applications to accommodate mobile visitors. The W3C (World Wide Web Consortium) is well aware of this trend and has introduced a number of APIs that help with this challenge. In this article, I will introduce you to one of these APIs, the Battery Status API.Read More…
  • Code
    JavaScript & AJAX
    JavaScript Animation That Works (Part 2 of 4)Spriting icon large
    In the last post, we introduced the idea of spriting, an easy way to animate in JavaScript that works in all browsers. We also walked through how to set up the sprite as a background image for a div and then use a line of JavaScript to change the background position to make it appear as if the image has moved. Read More…
  • Code
    PHP
    Validation and Exception Handling: From the UI to the BackendProcedural to oop php retina preview
    Sooner or later in your programming career you will be faced with the dilemma of validation and exception handling. This was the case with me and my team also. A couple or so years ago we reached a point when we had to take architectural actions to accommodate all the exceptional cases our quite large software project needed to handle. Below is a list of practices we came to value and apply when it comes to validation and exception handling.Read More…
  • Code
    JavaScript & AJAX
    Ember.js TestingEmber components retina preview
    When I started playing around with Ember.js almost a year ago, the testability story left something to be desired. You could unit test an object without any trouble, but a unit test is only one way to get feedback when you're building a software product. In addition to unit tests, I wanted a way to verify the integration of multiple components. So like most people testing rich JavaScript applications, I reached for the mother of all testing tools, Selenium.Read More…
  • Code
    JavaScript & AJAX
    Testing in Node.jsNodejs testing chai retina preview
    A test driven development cycle simplifies the thought process of writing code, makes it easier, and quicker in the long run. But just writing tests is not enough by itself, knowing the kinds of tests to write and how to structure code to conform to this pattern is what it's all about. In this article we will take a look at building a small app in Node.js following a TDD pattern.Read More…
  • Code
    JavaScript & AJAX
    JavaScript ObjectsCover
    In JavaScript, objects are king: Almost everything is an object or acts like an object. Understand objects and you will understand JavaScript. So let's examine the creation of objects in JavaScript.Read More…