From 6f23e706d7f1cdded5a16fdb8bb1518104f80184 Mon Sep 17 00:00:00 2001 From: Stephan Ferlin-Reiter Date: Tue, 2 Jul 2024 20:07:28 +0000 Subject: [PATCH] Improve the error message of the toHaveSize matcher. We include the size of the thing that didn't meet the size expectation. --- spec/core/matchers/toHaveSizeSpec.js | 11 +++++++++++ src/core/matchers/toHaveSize.js | 25 +++++++++++++++++++++---- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/spec/core/matchers/toHaveSizeSpec.js b/spec/core/matchers/toHaveSizeSpec.js index c708a5b7..218b6178 100644 --- a/spec/core/matchers/toHaveSizeSpec.js +++ b/spec/core/matchers/toHaveSizeSpec.js @@ -15,6 +15,17 @@ describe('toHaveSize', function() { expect(result.pass).toBe(false); }); + it('informs about the size of an array whose length does not match', function() { + const matcher = jasmineUnderTest.matchers.toHaveSize({ + pp: jasmineUnderTest.makePrettyPrinter() + }), + result = matcher.compare([1, 2, 3], 2); + + expect(result.message()).toEqual( + 'Expected [ 1, 2, 3 ] with size 3 to have size 2.' + ); + }); + it('passes for an object with the proper number of keys', function() { const matcher = jasmineUnderTest.matchers.toHaveSize(), result = matcher.compare({ a: 1, b: 2 }, 2); diff --git a/src/core/matchers/toHaveSize.js b/src/core/matchers/toHaveSize.js index 05234cca..8a653448 100644 --- a/src/core/matchers/toHaveSize.js +++ b/src/core/matchers/toHaveSize.js @@ -9,7 +9,7 @@ getJasmineRequireObj().toHaveSize = function(j$) { * array = [1,2]; * expect(array).toHaveSize(2); */ - function toHaveSize() { + function toHaveSize(matchersUtil) { return { compare: function(actual, expected) { const result = { @@ -24,12 +24,29 @@ getJasmineRequireObj().toHaveSize = function(j$) { throw new Error('Cannot get size of ' + actual + '.'); } + let actualSize; if (j$.isSet(actual) || j$.isMap(actual)) { - result.pass = actual.size === expected; + actualSize = actual.size; } else if (isLength(actual.length)) { - result.pass = actual.length === expected; + actualSize = actual.length; } else { - result.pass = Object.keys(actual).length === expected; + actualSize = Object.keys(actual).length; + } + + result.pass = actualSize === expected; + + if (!result.pass) { + result.message = function() { + return ( + 'Expected ' + + matchersUtil.pp(actual) + + ' with size ' + + actualSize + + ' to have size ' + + expected + + '.' + ); + }; } return result;