Test tools¶
To make it easier to test code, and to ensure that example code is correct, there is a small testtools.js file in the work folder.
How to write tests¶
To prepare a test create a file like this. It’s also in the work folder. (For real examples the file will give assert a more interesting argument, whose truth or falsity is perhaps not obvious.)
TEST('all-pass', function()
{
assert( 2 + 2 === 4 );
assert( 'the ' + 'cat' === 'the cat');
});
TEST('2-4-fail', function()
{
assert( true );
assert( false );
assert( 1 );
assert( 0 );
});
How to run tests¶
Here’s how to run the tests at the command line, finishing with a command prompt that allows you inspect the state and also run the test again.
Rhino¶
For Rhino use load to run the test again.
core-javascript-work$ js -f testtools.js -f demo_testtools.js -f -
Testing: all-pass
Testing: 2-4-fail
! assert 2 has failed
! assert 4 has failed
Rhino 1.7 release 2 2010 01 20
js> load('demo_testtools.js') // You type this.
Testing: all-pass
Testing: 2-4-fail
! assert 2 has failed
! assert 4 has failed
js>
JSDB¶
For JSDB use run to run the test again.
C:core-javascript-work> jsdb -load testtools.js -load demo_testtools.js
Testing: all-pass
Testing: 2-4-fail
! assert 2 has failed
! assert 4 has failed
js> load('demo_testtools.js') // You type this.
Testing: all-pass
Testing: 2-4-fail
! assert 2 has failed
! assert 4 has failed
js>
testools.js¶
(Optional on a first reading.) Here’s the file testools.js. It’s short and simple (and has a not-nice dependency on global variables). It also has a branch based on whether it’s being run on JSDB or Rhino.
var telltail = 'global';
var _assertion_count = 0;
// Define a global function 'log'.
var log;
if (this.hasOwnProperty('jsArguments')){
log = function(s){
print(s + '\n');
};
} else {
log = print;
}
//
var TEST = function(title, code){
var x;
log( 'Testing: ' + title );
_assertion_count = 0;
try {
code();
} catch (x) {
log('! Exception at ' + x.fileName +':' + x.lineNumber);
log('! [' + x.name + '] ' + x.message );
}
};
var assert = function(arg){
_assertion_count += 1;
if (!arg){
var msg = '! assert ' + _assertion_count + ' has failed';
log(msg);
}
};