Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support negative indices in getCall #2199

Merged
merged 2 commits into from Jan 16, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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
7 changes: 6 additions & 1 deletion lib/sinon/proxy.js
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;
mjcrouch marked this conversation as resolved.
Show resolved Hide resolved
}
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