From 271908a2c488092ece6d7b1045bf605165b7305e Mon Sep 17 00:00:00 2001 From: Beat Richartz Date: Thu, 25 May 2017 10:08:33 +0100 Subject: [PATCH] Fail when one of the arguments passed into toBeCloseTo matcher is null --- spec/core/matchers/toBeCloseToSpec.js | 16 ++++++++++++++++ src/core/matchers/toBeCloseTo.js | 6 ++++++ 2 files changed, 22 insertions(+) diff --git a/spec/core/matchers/toBeCloseToSpec.js b/spec/core/matchers/toBeCloseToSpec.js index 8c892958..a0eca07f 100644 --- a/spec/core/matchers/toBeCloseToSpec.js +++ b/spec/core/matchers/toBeCloseToSpec.js @@ -29,6 +29,22 @@ describe("toBeCloseTo", function() { expect(result.pass).toBe(true); }); + it("fails when one of the arguments is null", function() { + var matcher = jasmineUnderTest.matchers.toBeCloseTo(); + + expect(function() { + matcher.compare(null, null); + }).toThrowError('Cannot use toBeCloseTo with null. Arguments evaluated to: expect(null).toBeCloseTo(null).'); + + expect(function() { + matcher.compare(0, null); + }).toThrowError('Cannot use toBeCloseTo with null. Arguments evaluated to: expect(0).toBeCloseTo(null).'); + + expect(function() { + matcher.compare(null, 0); + }).toThrowError('Cannot use toBeCloseTo with null. Arguments evaluated to: expect(null).toBeCloseTo(0).'); + }); + it("rounds expected values", function() { var matcher = jasmineUnderTest.matchers.toBeCloseTo(), result; diff --git a/src/core/matchers/toBeCloseTo.js b/src/core/matchers/toBeCloseTo.js index 5f3d7d84..94f7c4ec 100644 --- a/src/core/matchers/toBeCloseTo.js +++ b/src/core/matchers/toBeCloseTo.js @@ -15,6 +15,12 @@ getJasmineRequireObj().toBeCloseTo = function() { precision = precision || 2; } + if (expected === null || actual === null) { + throw new Error('Cannot use toBeCloseTo with null. Arguments evaluated to: ' + + 'expect(' + actual + ').toBeCloseTo(' + expected + ').' + ); + } + return { pass: Math.abs(expected - actual) < (Math.pow(10, -precision) / 2) };