Skip to content

Instantly share code, notes, and snippets.

@Klortho
Last active June 23, 2016 04:59
Show Gist options
  • Save Klortho/1b93041808e9174a31c430b61fe568b0 to your computer and use it in GitHub Desktop.
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
// 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