My favorites | Sign in
Project Logo
             
Search
for
Updated Mar 08, 2008 by bienhd
Labels: featured, phase-deploy
GettingStarted  
A quick start guide on how to use jstest

jstest is a lightweight unit testing library for Javascript code. Unit testing is a great tool to consistently uncover bugs in programming code. jstest.js introduces two variables into the global namespace:

  • assert
  • jstest

asserting your code

When you "assert" an expression, it means you believe that expression should be true. If that expression is false, an error message will be printed out telling you so. assert takes in two arguments, your expression/value and an optional error message. For example:

var x = 1;
var y = 2;

assert(x == y);			// fails, prints out a standard error message
assert(x == x);			// passes, you have nothing to worry about

assert(x == y, "my own error message");		// fails and prints out your special error message
assert(y == y, "my special error message"); // passes and nothing prints out

running your tests

To run your tests, create a new HTML file and include jstest.js. Inside

 tags, call the jstest function like this:
 

<!-- Use jstest inside a normal HTML file in PRE tags -->
<pre style="background: #000; color: #fff;">
<script src="text/javascript">
jstest("Describe your test case here", {
    setup: function(){
        // this code runs BEFORE each test
    },

    teardown: function(){
        // this code runs AFTER each test
    },

    testTruth: function(){
        // any function that starts with 'test' will be executed
        assert(true, "true should be true");
        assert(false, "false should be true");
    }
});
</script>
</pre>

jstest will run any functions that start with "test". Inside each of these functions are where calls to assert should be made. If any asserts are passed a false/null expression, an error will be thrown and written out to your document. An error will also be written out if there are any uncaught exceptions.

The setup and teardown functions are special names that are recognized by jstest. jstest will run setup before each test. After each test, the teardown function will be called. This is useful if your tests have common code like setting up an object or class.

that's it

That pretty much covered all of the jstest library. Good luck with your unit testing!


Sign in to add a comment
Hosted by Google Code