Skip to content

Commit

Permalink
Add firstCall convenience property to get the first argument of the l…
Browse files Browse the repository at this point in the history
…ast call of a fake.
  • Loading branch information
Katrina Theodosopoulos committed Oct 31, 2019
1 parent 0e7c474 commit 068757d
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 1 deletion.
16 changes: 16 additions & 0 deletions docs/release-source/release/fakes.md
Expand Up @@ -152,6 +152,22 @@ f.lastCall.callback === cb2;
// true
```

#### `f.firstArg`

This property is a convenient way to get a reference to the first argument passed in the last call to the fake.

```js
var f = sinon.fake();
var date1 = new Date();
var date2 = new Date();

f(date1, 1, 2);
f(date2, 1, 2);

f.firstArg === date2;
// true
```

#### `f.lastArg`

This property is a convenient way to get a reference to the last argument passed in the last call to the fake.
Expand Down
9 changes: 8 additions & 1 deletion lib/sinon/fake.js
Expand Up @@ -14,9 +14,16 @@ var uuid = 0;
function wrapFunc(f) {
var proxy;
var fakeInstance = function() {
var lastArg = arguments.length > 0 ? arguments[arguments.length - 1] : undefined;
var firstArg, lastArg;

if (arguments.length > 0) {
firstArg = arguments[0];
lastArg = arguments[arguments.length - 1];
}

var callback = lastArg && typeof lastArg === "function" ? lastArg : undefined;

proxy.firstArg = firstArg;
proxy.lastArg = lastArg;
proxy.callback = callback;

Expand Down
29 changes: 29 additions & 0 deletions test/fake-test.js
Expand Up @@ -133,6 +133,35 @@ describe("fake", function() {
});
});

describe(".firstArg", function() {
it("should be the first argument from the last call", function() {
var f = fake();
f(41, 42, 43);
assert.equals(f.firstArg, 41);

f(44, 45);
assert.equals(f.firstArg, 44);

f(46);
assert.equals(f.firstArg, 46);

f(false, true, 47, "string");
assert.equals(f.firstArg, false);

f("string", false, true, 47);
assert.equals(f.firstArg, "string");

f(47, "string", false, true);
assert.equals(f.firstArg, 47);

f(true, 47, "string", false);
assert.equals(f.firstArg, true);

f();
assert.isUndefined(f.firstArg);
});
});

describe(".lastArg", function() {
it("should be the last argument from the last call", function() {
var f = fake();
Expand Down

0 comments on commit 068757d

Please sign in to comment.