1. Code
  2. JavaScript

Quick and Easy JavaScript Testing with “Assert”


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

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

Test 2: Closures

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.


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?

Looking for something to help kick start your next project?