Javascript – How does one unit test an algorithm

algorithmsjavascriptunit testing

I was recently working on a JS slideshow which rotates images using a weighted average algorithm. Thankfully, timgilbert has written a weighted list script which implements the exact algorithm I needed. However in his documentation he's noted under todos: "unit tests!".

I'd like to know is how one goes about unit testing an algorithm. In the case of a weighted average how would you create a proof that the averages are accurate when there is the element of randomness?

Code samples of similar would be very helpful to my understanding.

Best Answer

There a couple of technique you can use here:

1) Replace the random number generator with one that produces canned values, and check that the expected values are gotten

   old_random = Math.random;
   Math.random = function() { return 0.5; };
   assert_equals(random_pick(), expected_random_pick);

2) Run the algorithm a whole lots of times, and sum up the results

weights = {0:.1, 2:.5, 6:0.4}
totals = {}
count = 10000;
for(x = 0; x < count; x++)
{
    totals[random_pick(weights)] += 1 / count;
}
assert(totals[0] - weights[0] < 0.1)
assert(totals[2] - weights[2] < 0.1)
assert(totals[6] - weights[6] < 0.1)

The idea here is that if you run the algorithm enough times the law of large numbers will make the totals similar the theoretically expected ones. Then you check that.

Related Topic