Skip to content

Commit

Permalink
Make calledWith() assertions idempotent (#2407)
Browse files Browse the repository at this point in the history
* 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.
  • Loading branch information
cincodenada authored Nov 3, 2021
1 parent 383b083 commit e78a670
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 12 deletions.
22 changes: 11 additions & 11 deletions lib/sinon/spy-formatters.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 13 additions & 1 deletion test/assert-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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:`
);
});
Expand All @@ -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);
Expand Down

0 comments on commit e78a670

Please sign in to comment.