Change toBeCloseTo matcher to be more consistent.

It now calculates and compares a difference, rather than rounding
two separate quantities and testing for their equality.
This commit is contained in:
Dave Burt
2012-07-31 15:03:55 +10:00
committed by Davis W. Frank & Rajan Agaskar
parent 6ac4b686a3
commit 5e594946bb
4 changed files with 9 additions and 10 deletions

View File

@@ -1445,10 +1445,7 @@ jasmine.Matchers.prototype.toBeCloseTo = function(expected, precision) {
if (!(precision === 0)) {
precision = precision || 2;
}
var multiplier = Math.pow(10, precision);
var actual = Math.round(this.actual * multiplier);
expected = Math.round(expected * multiplier);
return expected == actual;
return Math.abs(expected - this.actual) < (Math.pow(10, -precision) / 2);
};
/**
@@ -2537,5 +2534,5 @@ jasmine.version_= {
"major": 1,
"minor": 2,
"build": 0,
"revision": 1337006083
"revision": 1343710612
};

View File

@@ -510,6 +510,11 @@ describe("jasmine.Matchers", function() {
expect(-1.23).not.toBeCloseTo(-1.24);
});
it("expects close numbers to 'be close' and further numbers not to", function() {
expect(1.225).not.toBeCloseTo(1.234); // difference is 0.009
expect(1.225).toBeCloseTo(1.224); // difference is 0.001
});
it("accepts an optional precision argument", function() {
expect(1).toBeCloseTo(1.1, 0);
expect(1.2).toBeCloseTo(1.23, 1);

View File

@@ -302,10 +302,7 @@ jasmine.Matchers.prototype.toBeCloseTo = function(expected, precision) {
if (!(precision === 0)) {
precision = precision || 2;
}
var multiplier = Math.pow(10, precision);
var actual = Math.round(this.actual * multiplier);
expected = Math.round(expected * multiplier);
return expected == actual;
return Math.abs(expected - this.actual) < (Math.pow(10, -precision) / 2);
};
/**

View File

@@ -3,5 +3,5 @@ jasmine.version_= {
"major": 1,
"minor": 2,
"build": 0,
"revision": 1337006083
"revision": 1343710612
};