diff --git a/docs/release-source/release/spies.md b/docs/release-source/release/spies.md index b77f40fc2..be8a9b995 100644 --- a/docs/release-source/release/spies.md +++ b/docs/release-source/release/spies.md @@ -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.
diff --git a/lib/sinon/proxy.js b/lib/sinon/proxy.js index 7af3fb788..7b7807aad 100644 --- a/lib/sinon/proxy.js +++ b/lib/sinon/proxy.js @@ -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; } diff --git a/test/spy-test.js b/test/spy-test.js index 5c35d9d4d..3bbf50bab 100644 --- a/test/spy-test.js +++ b/test/spy-test.js @@ -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();