Skip to content

Commit

Permalink
Add restore method for stubbed property descriptors
Browse files Browse the repository at this point in the history
  • Loading branch information
lucasfcosta committed Mar 11, 2017
1 parent 5bbfa51 commit e852f4f
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 5 deletions.
9 changes: 4 additions & 5 deletions lib/sinon/stub.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,11 @@ function stub(object, property, descriptor) {
var s = stub.create(arity);
s.rootObj = object;
s.propName = property;
s.restore = function restore() {
Object.defineProperty(object, property, actualDescriptor);
};

if (isStubbingNonFuncProperty) {
return s;
}

return wrapMethod(object, property, s);
return isStubbingNonFuncProperty ? s : wrapMethod(object, property, s);
}

stub.createStubInstance = function (constructor) {
Expand Down
78 changes: 78 additions & 0 deletions test/stub-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2332,6 +2332,44 @@ describe("stub", function () {

assert.equals(myObj.prop, "bar");
});

it("can restore stubbed setters for functions", function () {
var propFn = function () {
return "bar";
};

var myObj = {
prop: propFn
};

var stub = createStub(myObj, "prop");

stub.get(function () {
return "baz";
});

stub.restore();

assert.equals(myObj.prop, propFn);
});

it("can restore stubbed getters for properties", function () {
var myObj = {
get prop() {
return "bar";
}
};

var stub = createStub(myObj, "prop");

stub.get(function () {
return "baz";
});

stub.restore();

assert.equals(myObj.prop, "bar");
});
});

describe(".set", function () {
Expand Down Expand Up @@ -2392,5 +2430,45 @@ describe("stub", function () {

assert.equals(myObj.example, "bar");
});

it("can restore stubbed setters for functions", function () {
var propFn = function () {
return "bar";
};

var myObj = {
prop: propFn
};

var stub = createStub(myObj, "prop");

stub.set(function () {
myObj.otherProp = "baz";
});

stub.restore();

assert.equals(myObj.prop, propFn);
});

it("can restore stubbed setters for properties", function () {
var myObj = { // eslint-disable-line accessor-pairs
set prop(val) {
this.otherProp = "bar";
return "bar";
}
};

var stub = createStub(myObj, "prop");

stub.set(function () {
myObj.otherProp = "baz";
});

stub.restore();

myObj.prop = "foo";
assert.equals(myObj.otherProp, "bar");
});
});
});

0 comments on commit e852f4f

Please sign in to comment.