Skip to content

Commit

Permalink
Add .lastArg and .callback to fake and call
Browse files Browse the repository at this point in the history
  • Loading branch information
mroderick committed Apr 30, 2018
1 parent 01cbe61 commit d5cd20f
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 1 deletion.
19 changes: 18 additions & 1 deletion lib/sinon/fake.js
Expand Up @@ -32,8 +32,25 @@ function cleanProxy(f) {
return f;
}

var uuid = 0;
function wrapFunc(f) {
return cleanProxy(spy(f));
var fakeInstance = function () {
var lastArg = arguments.length > 0 && arguments[arguments.length - 1] || undefined;
var callback = lastArg && typeof lastArg === "function" ? lastArg : undefined;

/* eslint-disable no-use-before-define */
p.lastArg = lastArg;
p.callback = callback;
/* eslint-enable no-use-before-define */

return f && f.apply(f, arguments);
};
var p = cleanProxy(spy(fakeInstance));

p.displayName = "fake";
p.id = "fake#" + uuid++;

return p;
}

function fake(f) {
Expand Down
61 changes: 61 additions & 0 deletions test/fake-test.js
Expand Up @@ -4,6 +4,7 @@ var sinon = require("../lib/sinon.js");
var fake = sinon.fake;
var referee = require("@sinonjs/referee");
var assert = referee.assert;
var refute = referee.refute;

referee.add("isProxy", {
assert: function assertIsProxy(actual) {
Expand Down Expand Up @@ -50,6 +51,66 @@ describe("fake", function () {
verifyProxy(fake);
});

describe(".callback", function () {
it("it should be a reference for the callback in the last call", function () {
var f = fake();
var callback1 = function () {};
var callback2 = function () {};

f(1, 2, 3, callback1);
assert.equals(f.callback, callback1);

f(1, 2, 3, callback2);
assert.equals(f.callback, callback2);

f(1, 2, 3);
assert.equals(f.callback, undefined);
});
});

describe(".displayName", function () {
it("should be 'fake'", function () {
var fakes = [
fake(),
fake.returns(42),
fake.throws(new Error()),
fake.resolves(42),
fake.rejects(new Error()),
fake.yields(42),
fake.yieldsAsync(42)
];

fakes.forEach(function (f) {
assert.equals(f.displayName, "fake");
});
});
});

describe(".id", function () {
it("should start with 'fake#'", function () {
for (var i = 0; i < 100; i++) {
assert.isTrue(fake().id.indexOf("fake#") === 0);
}
});
});

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

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

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

f();
refute.defined(f.lastArg);
});
});

describe(".returns", function () {
it("should return a function that returns the argument", function () {
var expected = 42;
Expand Down

0 comments on commit d5cd20f

Please sign in to comment.