Skip to content

Commit

Permalink
Merge pull request #2199 from RealZogger/getCall-negative
Browse files Browse the repository at this point in the history
Support negative indices in getCall
  • Loading branch information
fatso83 authored Jan 16, 2020
2 parents 2369139 + d851a5e commit 7c79e80
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 1 deletion.
2 changes: 2 additions & 0 deletions docs/release-source/release/spies.md
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,8 @@ Returns `true` if spy always returned the provided value.

Returns the *nth* [call](#spycall).

If *n* is negative, the *nth* call from the end is returned. For example, `spy.getCall(-1)` returns the last call, and `spy.getCall(-2)` returns the second to last call.

Accessing individual calls helps with more detailed behavior verification when the spy is called more than once.

<div data-example-id="spies-8-spy-call"></div>
Expand Down
7 changes: 6 additions & 1 deletion lib/sinon/proxy.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,12 @@ var proxyApi = {
return emptyFakes;
},

getCall: function getCall(i) {
getCall: function getCall(index) {
var i = index;
if (i < 0) {
// Negative indices means counting backwards from the last call
i += this.callCount;
}
if (i < 0 || i >= this.callCount) {
return null;
}
Expand Down
42 changes: 42 additions & 0 deletions test/spy-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2086,6 +2086,48 @@ describe("spy", function() {
});
});

describe(".getCall", function() {
it("is null for indexes >= length", function() {
var spy = createSpy();

spy();

assert.isNull(spy.getCall(1));
assert.isNull(spy.getCall(2));
});

it("is null for indexes < -length", function() {
var spy = createSpy();

spy();

assert.isNull(spy.getCall(-2));
assert.isNull(spy.getCall(-3));
});

it("is same as last call when passed index -1", function() {
var spy = createSpy();

spy();
spy();
spy();

assert.same(spy.getCall(-1).callId, spy.lastCall.callId);
assert.same(spy.getCall(-1).spy, spy.lastCall.spy);
});

it("is same as n-1th call when passed index -2", function() {
var spy = createSpy();

spy();
spy();
spy();

assert.same(spy.getCall(-2).callId, spy.getCall(1).callId);
assert.same(spy.getCall(-2).spy, spy.getCall(1).spy);
});
});

describe(".lastCall", function() {
it("is undefined by default", function() {
var spy = createSpy();
Expand Down

0 comments on commit 7c79e80

Please sign in to comment.