Skip to content

Instantly share code, notes, and snippets.

@UnwashedMeme
Last active August 29, 2015 14:13
Show Gist options
  • Save UnwashedMeme/8dd446062a5da005bace to your computer and use it in GitHub Desktop.
Save UnwashedMeme/8dd446062a5da005bace to your computer and use it in GitHub Desktop.
toBeCloseToArray for jasmine 2
beforeEach(function() {
jasmine.addMatchers({
toBeCloseToArray: function(util, customEqualityTesters) {
return {
compare: function(actual, expected, precision) {
if (precision !== 0) {
precision = precision || 2;
}
var i;
return {
pass: _.every(expected, function(v, idx) {
i = idx;
return Math.abs(actual[idx] - v) < (Math.pow(10, -precision) / 2);
}),
message: 'Index ' + i + ', ' + actual[i] +
' should be within ' + (Math.pow(10, -precision) / 2) +
' of ' + expected[i]
};
}
};
}
});
});
describe('toBeCloseToArray', function() {
it('should be close', function() {
expect([1.0, 1.5, 2.0]).toBeCloseToArray([1.001, 1.5, 1.9999]);
expect([1.0, 1.5, 2.0]).toBeCloseToArray([1.001, 1.5, 1.6], 0);
expect([1.0, 1.5, 2.0]).toBeCloseToArray([1.001, 1.5, 1.96], 1);
});
it('should not be close', function() {
expect([1.0, 1.5, 2.0]).not.toBeCloseToArray([1.001, 1.5, 1.9999], 10);
expect([1.0, 1.5, 2.0]).not.toBeCloseToArray([2, 1.5, 1.9], 1);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment