At its most basic level, Unit Testing in any language provides assertions against some known or expected output.
function assert( outcome, description ) {
var passFail = outcome ? 'pass' : 'fail';
console.log(passFail, ': ', description);
return outcome;
};
The popular assertion method above shows us one quick and easy way to assert a value in most web browsers and interpreters like Node.js with virtually any version of ECMAScript.
A good unit test is designed to test a discreet unit of code; usually a function.
function add(num1, num2) {
return num1 + num2;
}
var result = add(5, 20);
assert( result == 24, 'add(5, 20) should return 25...');
In the example above, the return value from the function add(x, y)
or 5 + 20
is clearly 25
, so our assertion of 24
should fail, and the assert method will log a "fail" line.
If we simply modify our expected assertion outcome, the test will succeed and the resulting output would look something like this.
assert( result == 25, 'add(5, 20) should return 25...');
console output:
> pass: should return 25...
This simple assertion can assure that in many different cases, your "add" function will always return the expected result and requires no additional frameworks or libraries to work.
A more rigorous set of assertions would look like this (using var result = add(x,y)
for each assertion):
assert( result == 0, 'add(0, 0) should return 0...');
assert( result == -1, 'add(0, -1) should return -1...');
assert( result == 1, 'add(0, 1) should return 1...');
And console output would be this:
> pass: should return 0...
> pass: should return -1...
> pass: should return 1...
We can now safely say that add(x,y)
… should return the sum of two integers. We can roll these up into something like this:
function test__addsIntegers() {
// expect a number of passed assertions
var passed = 3;
// number of assertions to be reduced and added as Booleans
var assertions = [
assert( add(0, 0) == 0, 'add(0, 0) should return 0...'),
assert( add(0, -1) == -1, 'add(0, -1) should return -1...'),
assert( add(0, 1) == 1, 'add(0, 1) should return 1...')
].reduce(function(previousValue, currentValue){
return previousValue + current;
});
if (assertions === passed) {
console.log("add(x,y)... did return the sum of two integers");
return true;
} else {
console.log("add(x,y)... does not reliably return the sum of two integers");
return false;
}
}