From b170693c5d8e73286f38e499a0ba91ee9bafa1bb Mon Sep 17 00:00:00 2001 From: Marcin Chrzanowski Date: Mon, 10 Jul 2017 14:04:25 -0400 Subject: Add variance tests --- __tests__/dice.test.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/__tests__/dice.test.js b/__tests__/dice.test.js index 489750f..45c859b 100644 --- a/__tests__/dice.test.js +++ b/__tests__/dice.test.js @@ -37,6 +37,19 @@ expect.extend({ `expected all to${pass ? ' not ' : ' '}be equal to ${expected}` ) } + }, + toHaveVariance(received, expected, margin = 0.5) { + const average = received.reduce(plus) / received.length + const variance = received.map((value) => (Math.pow(value - average, 2))) + .reduce(plus) / (received.length - 1) + const pass = variance > expected - margin && variance < expected + margin + + return { + pass, + message: () => ( + `expected variance to${pass ? ' not ' : ' '}be around ${expected} (margin: ${margin}), got ${variance}` + ) + } } }) @@ -72,6 +85,14 @@ const testDie = (die, testSpecs, numberRolls = defaultNumberRolls) => { }) } + if ('variance' in testSpecs) { + let { variance, margin } = testSpecs.variance + + it(`has a variance of ${variance}`, () => { + expect(rolls).toHaveVariance(variance, margin) + }) + } + if ('bounds' in testSpecs) { let { low, high, expectExtrema } = testSpecs.bounds -- cgit v1.2.3