Skip to content

Commit e78a670

Browse files
authored
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.
1 parent 383b083 commit e78a670

File tree

2 files changed

+24
-12
lines changed

2 files changed

+24
-12
lines changed

lib/sinon/spy-formatters.js

+11-11
Original file line numberDiff line numberDiff line change
@@ -72,29 +72,29 @@ module.exports = {
7272
j < calledArgs.length || j < expectedArgs.length;
7373
++j
7474
) {
75-
if (calledArgs[j]) {
76-
calledArgs[j] = quoteStringValue(calledArgs[j]);
75+
var calledArg = calledArgs[j];
76+
var expectedArg = expectedArgs[j];
77+
if (calledArg) {
78+
calledArg = quoteStringValue(calledArg);
7779
}
7880

79-
if (expectedArgs[j]) {
80-
expectedArgs[j] = quoteStringValue(expectedArgs[j]);
81+
if (expectedArg) {
82+
expectedArg = quoteStringValue(expectedArg);
8183
}
8284

8385
message += "\n";
8486

8587
var calledArgMessage =
86-
j < calledArgs.length ? sinonFormat(calledArgs[j]) : "";
87-
if (match.isMatcher(expectedArgs[j])) {
88+
j < calledArgs.length ? sinonFormat(calledArg) : "";
89+
if (match.isMatcher(expectedArg)) {
8890
message += colorSinonMatchText(
89-
expectedArgs[j],
90-
calledArgs[j],
91+
expectedArg,
92+
calledArg,
9193
calledArgMessage
9294
);
9395
} else {
9496
var expectedArgMessage =
95-
j < expectedArgs.length
96-
? sinonFormat(expectedArgs[j])
97-
: "";
97+
j < expectedArgs.length ? sinonFormat(expectedArg) : "";
9898
var diff = jsDiff.diffJson(
9999
calledArgMessage,
100100
expectedArgMessage

test/assert-test.js

+13-1
Original file line numberDiff line numberDiff line change
@@ -2172,7 +2172,7 @@ describe("assert", function () {
21722172
"expected doSomething to be called once and with exact arguments \n" +
21732173
"Call 1:\n"
21742174
}${color.red("4")}\n${color.red("3")}\n${color.red(
2175-
inspect(JSON.stringify('"bob"'))
2175+
inspect('"bob"')
21762176
)}\nCall 2:`
21772177
);
21782178
});
@@ -2188,6 +2188,18 @@ describe("assert", function () {
21882188
);
21892189
});
21902190

2191+
it("assert.calledWith message is idempotent", function () {
2192+
this.obj.doSomething("hey");
2193+
2194+
this.message("calledWith", this.obj.doSomething, "");
2195+
this.message("calledWith", this.obj.doSomething, "");
2196+
this.message("calledWith", this.obj.doSomething, "");
2197+
assert.contains(
2198+
this.message("calledWith", this.obj.doSomething, ""),
2199+
'"hey"'
2200+
);
2201+
});
2202+
21912203
it("assert.alwaysCalledWithExactly exception message", function () {
21922204
this.obj.doSomething(1, 3, "hey");
21932205
this.obj.doSomething(1, 3);

0 commit comments

Comments
 (0)