Skip to content

Commit e852f4f

Browse files
committed
Add restore method for stubbed property descriptors
1 parent 5bbfa51 commit e852f4f

2 files changed

Lines changed: 82 additions & 5 deletions

File tree

lib/sinon/stub.js

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -44,12 +44,11 @@ function stub(object, property, descriptor) {
4444
var s = stub.create(arity);
4545
s.rootObj = object;
4646
s.propName = property;
47+
s.restore = function restore() {
48+
Object.defineProperty(object, property, actualDescriptor);
49+
};
4750

48-
if (isStubbingNonFuncProperty) {
49-
return s;
50-
}
51-
52-
return wrapMethod(object, property, s);
51+
return isStubbingNonFuncProperty ? s : wrapMethod(object, property, s);
5352
}
5453

5554
stub.createStubInstance = function (constructor) {

test/stub-test.js

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2332,6 +2332,44 @@ describe("stub", function () {
23322332

23332333
assert.equals(myObj.prop, "bar");
23342334
});
2335+
2336+
it("can restore stubbed setters for functions", function () {
2337+
var propFn = function () {
2338+
return "bar";
2339+
};
2340+
2341+
var myObj = {
2342+
prop: propFn
2343+
};
2344+
2345+
var stub = createStub(myObj, "prop");
2346+
2347+
stub.get(function () {
2348+
return "baz";
2349+
});
2350+
2351+
stub.restore();
2352+
2353+
assert.equals(myObj.prop, propFn);
2354+
});
2355+
2356+
it("can restore stubbed getters for properties", function () {
2357+
var myObj = {
2358+
get prop() {
2359+
return "bar";
2360+
}
2361+
};
2362+
2363+
var stub = createStub(myObj, "prop");
2364+
2365+
stub.get(function () {
2366+
return "baz";
2367+
});
2368+
2369+
stub.restore();
2370+
2371+
assert.equals(myObj.prop, "bar");
2372+
});
23352373
});
23362374

23372375
describe(".set", function () {
@@ -2392,5 +2430,45 @@ describe("stub", function () {
23922430

23932431
assert.equals(myObj.example, "bar");
23942432
});
2433+
2434+
it("can restore stubbed setters for functions", function () {
2435+
var propFn = function () {
2436+
return "bar";
2437+
};
2438+
2439+
var myObj = {
2440+
prop: propFn
2441+
};
2442+
2443+
var stub = createStub(myObj, "prop");
2444+
2445+
stub.set(function () {
2446+
myObj.otherProp = "baz";
2447+
});
2448+
2449+
stub.restore();
2450+
2451+
assert.equals(myObj.prop, propFn);
2452+
});
2453+
2454+
it("can restore stubbed setters for properties", function () {
2455+
var myObj = { // eslint-disable-line accessor-pairs
2456+
set prop(val) {
2457+
this.otherProp = "bar";
2458+
return "bar";
2459+
}
2460+
};
2461+
2462+
var stub = createStub(myObj, "prop");
2463+
2464+
stub.set(function () {
2465+
myObj.otherProp = "baz";
2466+
});
2467+
2468+
stub.restore();
2469+
2470+
myObj.prop = "foo";
2471+
assert.equals(myObj.otherProp, "bar");
2472+
});
23952473
});
23962474
});

0 commit comments

Comments
 (0)