Skip to content

Instantly share code, notes, and snippets.

@sampottinger
Last active December 11, 2015 01:49
Show Gist options
  • Save sampottinger/4526017 to your computer and use it in GitHub Desktop.
Save sampottinger/4526017 to your computer and use it in GitHub Desktop.
Simple routine to run a list of tests on mathematical functions where each test checks the return value for equality against a known value using a list of predefined parameters. Requires http://www.diveintojavascript.com/projects/javascript-sprintf. Released under GNU GPL.
function addAll(a, b, c)
{
return a + b + c;
}
function multiplyAll(a, b, c)
{
return a * b * c;
}
var suiteDefns =
[
{name: "testAddAll", method: addAll, tests:
[
{params:[2, 3, 4], expected_val: 10, tollerance:0},
{params:[5, 6, 7], expected_val: 18, tollerance:0}
]
},
{name: "testMultipleAll", method: multiplyAll, tests:
[
{params:[2, 3, 4], expected_val: 24, tollerance:0},
{params:[5, 6, 7], expected_val: 210, tollerance:0}
]
}
]
function testCalculation(suiteDefn)
{
var name = suiteDefn.name;
var method = suiteDefn.method;
var tests = suiteDefn.tests;
for(var i in tests)
{
var test = tests[i];
var params = test.params;
var expected = test.expected_val;
var tollerance = test.tollerance;
var result = method.apply(this, params);
if(Math.abs(result - expected) > tollerance)
{
var errMsg = sprintf(
"Test %s failed (expected %f but got %f).",
name,
expected,
result
);
console.log(errMsg);
}
}
}
function runTests()
{
console.log("Running tests...");
for(var i in suiteDefns)
{
var suite = suiteDefns[i];
testCalculation(suite);
}
console.log("Tests complete.");
}
runTests();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment