From e78a670611682c7e35cf7d27887b409d6397d27c Mon Sep 17 00:00:00 2001 From: Joel Bradshaw Date: Wed, 3 Nov 2021 05:13:57 -0700 Subject: [PATCH] Make calledWith() assertions idempotent (#2407) * Add failing test for idempotent calledWith * Make calledWith() assertions idempotent Previously, calledWith() modified the list of arguments (called and expected) in place, so that repeated calls to calledWith() assertions ended up being repeatedly escaped. This fixes that behavior, copying the arguments out of the spy's internal array before modifying them. --- lib/sinon/spy-formatters.js | 22 +++++++++++----------- test/assert-test.js | 14 +++++++++++++- 2 files changed, 24 insertions(+), 12 deletions(-) diff --git a/lib/sinon/spy-formatters.js b/lib/sinon/spy-formatters.js index f39b2a9d6..58685453d 100644 --- a/lib/sinon/spy-formatters.js +++ b/lib/sinon/spy-formatters.js @@ -72,29 +72,29 @@ module.exports = { j < calledArgs.length || j < expectedArgs.length; ++j ) { - if (calledArgs[j]) { - calledArgs[j] = quoteStringValue(calledArgs[j]); + var calledArg = calledArgs[j]; + var expectedArg = expectedArgs[j]; + if (calledArg) { + calledArg = quoteStringValue(calledArg); } - if (expectedArgs[j]) { - expectedArgs[j] = quoteStringValue(expectedArgs[j]); + if (expectedArg) { + expectedArg = quoteStringValue(expectedArg); } message += "\n"; var calledArgMessage = - j < calledArgs.length ? sinonFormat(calledArgs[j]) : ""; - if (match.isMatcher(expectedArgs[j])) { + j < calledArgs.length ? sinonFormat(calledArg) : ""; + if (match.isMatcher(expectedArg)) { message += colorSinonMatchText( - expectedArgs[j], - calledArgs[j], + expectedArg, + calledArg, calledArgMessage ); } else { var expectedArgMessage = - j < expectedArgs.length - ? sinonFormat(expectedArgs[j]) - : ""; + j < expectedArgs.length ? sinonFormat(expectedArg) : ""; var diff = jsDiff.diffJson( calledArgMessage, expectedArgMessage diff --git a/test/assert-test.js b/test/assert-test.js index 95e49d8ad..7fcd282e5 100644 --- a/test/assert-test.js +++ b/test/assert-test.js @@ -2172,7 +2172,7 @@ describe("assert", function () { "expected doSomething to be called once and with exact arguments \n" + "Call 1:\n" }${color.red("4")}\n${color.red("3")}\n${color.red( - inspect(JSON.stringify('"bob"')) + inspect('"bob"') )}\nCall 2:` ); }); @@ -2188,6 +2188,18 @@ describe("assert", function () { ); }); + it("assert.calledWith message is idempotent", function () { + this.obj.doSomething("hey"); + + this.message("calledWith", this.obj.doSomething, ""); + this.message("calledWith", this.obj.doSomething, ""); + this.message("calledWith", this.obj.doSomething, ""); + assert.contains( + this.message("calledWith", this.obj.doSomething, ""), + '"hey"' + ); + }); + it("assert.alwaysCalledWithExactly exception message", function () { this.obj.doSomething(1, 3, "hey"); this.obj.doSomething(1, 3);