Skip to content

Commit

Permalink
Support negative indices in getCall
Browse files Browse the repository at this point in the history
This allows getting calls indexed from the end of the array
e.g. -1 gets the last call, -2 gets the penultimate call etc.
  • Loading branch information
mjcrouch committed Jan 15, 2020
1 parent 2369139 commit 6d59744
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 1 deletion.
2 changes: 2 additions & 0 deletions docs/release-source/release/spies.md
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
6 changes: 5 additions & 1 deletion lib/sinon/proxy.js
Expand Up @@ -40,7 +40,11 @@ var proxyApi = {
return emptyFakes;
},

getCall: function getCall(i) {
getCall: function getCall(index) {
var i = index;
if (i < 0) {
i += this.callCount;
}
if (i < 0 || i >= this.callCount) {
return null;
}
Expand Down
42 changes: 42 additions & 0 deletions test/spy-test.js
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 6d59744

Please sign in to comment.