Advertisement

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?

Advertisement