Last active
June 23, 2016 04:59
-
-
Save Klortho/1b93041808e9174a31c430b61fe568b0 to your computer and use it in GitHub Desktop.
Add `closeEnough` assertion to chai. See https://github.com/chaijs/chai/issues/89
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// DO NOT USE! | |
// This was a quick-and-dirty attempt to handle the problem. | |
// Use this package, instead: https://www.npmjs.com/package/nearlyequal | |
/* | |
const assert = require('chai').assert; | |
assert.closeEnough = function(actual, expected, message) { | |
const scale = Math.abs(actual)/2 + Math.abs(expected)/2; | |
if (scale === 0) return true; // guard against dividing by zero | |
const epsilon = Math.abs(actual - expected) / scale; | |
if (epsilon < 1E-13) return true; | |
assert.fail(actual, expected, message, 'closeEnough'); | |
}; | |
// To test: `node assert-close-enough.js --test` | |
if (typeof process === 'object' && process && 'argv' in process) { | |
const argv = process.argv; | |
if (argv.pop() === '--test') { | |
console.log('Testing ...'); | |
const cases = [2.3453434E23, 2.3453434E-23, 0.5]; | |
cases.forEach(function(expected) { | |
actual = Math.exp(Math.log(expected)); | |
assert.closeEnough(expected, actual, | |
'not closeEnough; expected: ' + expected + ', actual: ' + actual); | |
}); | |
console.log('all good'); | |
} | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment