From 7cbedcdda747bf425cca826ee8d3c8c7898dbd82 Mon Sep 17 00:00:00 2001 From: Teagan Durtschi Date: Sun, 21 Oct 2018 12:46:49 -0400 Subject: [PATCH] Add custom message for toBe() matcher when object equality check fails --- spec/core/matchers/toBeSpec.js | 21 ++++++++++++++++++++- src/core/matchers/toBe.js | 8 ++++++-- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/spec/core/matchers/toBeSpec.js b/spec/core/matchers/toBeSpec.js index 541eda96..d4179906 100644 --- a/spec/core/matchers/toBeSpec.js +++ b/spec/core/matchers/toBeSpec.js @@ -7,11 +7,30 @@ describe("toBe", function() { expect(result.pass).toBe(true); }); - it("fails when actual !== expected", function() { + it("fails with no message when actual !== expected", function() { var matcher = jasmineUnderTest.matchers.toBe(), result; result = matcher.compare(1, 2); expect(result.pass).toBe(false); + expect(result.message).toBeUndefined(); + }); + + it("fails with a custom message when expected is an array", function() { + var matcher = jasmineUnderTest.matchers.toBe(), + result; + + result = matcher.compare([1], [1]); + expect(result.pass).toBe(false); + expect(result.message).toBe("Expected [ 1 ] to be [ 1 ]. Tip: To check for deep equality, use .toEqual() instead of .toBe().") + }); + + it("fails with a custom message when expected is an object", function() { + var matcher = jasmineUnderTest.matchers.toBe(), + result; + + result = matcher.compare({foo: "bar"}, {foo: "bar"}); + expect(result.pass).toBe(false); + expect(result.message).toBe("Expected Object({ foo: 'bar' }) to be Object({ foo: 'bar' }). Tip: To check for deep equality, use .toEqual() instead of .toBe().") }); }); diff --git a/src/core/matchers/toBe.js b/src/core/matchers/toBe.js index bcbbb1a6..d7b9e593 100644 --- a/src/core/matchers/toBe.js +++ b/src/core/matchers/toBe.js @@ -1,4 +1,4 @@ -getJasmineRequireObj().toBe = function() { +getJasmineRequireObj().toBe = function($j) { /** * {@link expect} the actual value to be `===` to the expected value. * @function @@ -8,10 +8,14 @@ getJasmineRequireObj().toBe = function() { * expect(thing).toBe(realThing); */ function toBe() { + return { compare: function(actual, expected) { + var customMessage = 'Expected ' + $j.pp(expected) + ' to be ' + $j.pp(actual) + '. Tip: To check for deep equality, use .toEqual() instead of .toBe().'; + return { - pass: actual === expected + pass: actual === expected, + message: typeof expected === 'object' ? customMessage : undefined, }; } };