diff --git a/docs/release-source/release/spy-call.md b/docs/release-source/release/spy-call.md index 2563045b7..0eef1d5bb 100644 --- a/docs/release-source/release/spy-call.md +++ b/docs/release-source/release/spy-call.md @@ -83,6 +83,36 @@ The call's `this` value. Array of received arguments. +### `spyCall.callback` + +This property is a convenience for a call's callback. + +When the last argument in a call is a `Function`, then `callback` will reference that. Otherwise it will be `undefined`. + +```js +var spy = sinon.spy(); +var callback = function () {}; + +spy(1, 2, 3, callback); + +spy.lastCall.callback === callback; +// true +``` + +#### `spyCall.lastArg` + +This property is a convenience for the last argument of the call. + +```js +var spy = sinon.spy(); +var date = new Date(); + +spy(1, 2, date); + +spy.lastCall.lastArg === date; +// true +``` + ### `spyCall.exception` Exception thrown, if any. diff --git a/lib/sinon/call.js b/lib/sinon/call.js index c92b25ea2..96baad3e8 100644 --- a/lib/sinon/call.js +++ b/lib/sinon/call.js @@ -222,10 +222,16 @@ function createSpyCall(spy, thisValue, args, returnValue, exception, id, errorWi if (typeof id !== "number") { throw new TypeError("Call id is not a number"); } + var proxyCall = Object.create(callProto); + var lastArg = args.length > 0 && args[args.length - 1] || undefined; + var callback = lastArg && typeof lastArg === "function" ? lastArg : undefined; + proxyCall.proxy = spy; proxyCall.thisValue = thisValue; proxyCall.args = args; + proxyCall.lastArg = lastArg; + proxyCall.callback = callback; proxyCall.returnValue = returnValue; proxyCall.exception = exception; proxyCall.callId = id; diff --git a/test/call-test.js b/test/call-test.js index a743e40e2..766a66162 100644 --- a/test/call-test.js +++ b/test/call-test.js @@ -435,6 +435,41 @@ describe("sinonSpy.call", function () { }); }); + describe(".callback", function () { + it("it should be a reference for the callback", function () { + var spy = sinonSpy(); + var callback1 = function () {}; + var callback2 = function () {}; + + spy(1, 2, 3, callback1); + assert.equals(spy.getCall(0).callback, callback1); + + spy(1, 2, 3, callback2); + assert.equals(spy.getCall(1).callback, callback2); + + spy(1, 2, 3); + assert.equals(spy.getCall(2).callback, undefined); + }); + }); + + describe(".lastArg", function () { + it("should be the last argument from the call", function () { + var spy = sinonSpy(); + + spy(41, 42, 43); + assert.equals(spy.getCall(0).lastArg, 43); + + spy(44, 45); + assert.equals(spy.getCall(1).lastArg, 45); + + spy(46); + assert.equals(spy.getCall(2).lastArg, 46); + + spy(); + assert.equals(spy.getCall(3).lastArg, undefined); + }); + }); + describe("call.yieldTest", function () { beforeEach(spyCallCallSetup);