Skip to content

Snippets: Random testing in JavaScript

Benjamin Kästner edited this page Apr 24, 2015 · 5 revisions
/**
 * @brief Tests a user defined function against a reference function.
 * @param generator is a generator for random arguments, it must return an array
 * @param userSolution is the solution provided by the user
 * @param referenceSolution is the solution provided by the original kata author
 * @param tests is the number of tests (optional)
 *
 * The `referenceSolution` should be pure, it shouldn't modify it's arguments, 
 * since `userSolution` will work on the same array afterwards.
 *
 * The values are compared via equality (===), and the number of shown tests is
 * limited to three. 
*/
var randomAssertEquals = function(generator, userSolution, referenceSolution, tests){
	tests = tests || 100;
	var i = 0, user, reference, values;
	while( tests --> 0){
		values = generator();
		reference = referenceSolution.apply(this, values);
		user      = userSolution.apply(this,      values);
		if(i++ < 3){
			Test.assertEquals(user, reference, "didn't work on the following argument array: " + values);
		} else if(reference !== user){
			Test.assertEquals(user, reference, "didn't work on the following argument array: " + values);
		}
	}
}

/**
 * @brief Tests a user defined function against a reference function.
 * @param generator is a generator for random arguments, it must return an array
 * @param userSolution is the solution provided by the user
 * @param referenceSolution is the solution provided by the original kata author
 * @param tests is the number of tests (optional)
 *
 * The `referenceSolution` should be pure, it shouldn't modify it's arguments, 
 * since `userSolution` will work on the same array afterwards.
 *
 * The values are compared via equality (===), and the number of shown tests is
 * limited to three. 
*/
var randomAssertSimilar = function(generator, userSolution, referenceSolution, tests){
	tests = tests || 100;
	var user, reference, values;
	while( tests --> 0){
		values = generator();
		reference = referenceSolution.apply(this, values);
		user      = userSolution.apply(this,      values);		
		Test.assertSimilar(user, reference, "didn't work on the following argument array: " + values);		
	}
}
Clone this wiki locally