diff --git a/src/stub.ts b/src/stub.ts index a6f7ffe..1a03ea0 100644 --- a/src/stub.ts +++ b/src/stub.ts @@ -1,31 +1,17 @@ -import * as _ from 'lodash' +import * as sinon from 'sinon' /** * mocks an object's property */ -export default function (object: T, path: K, value: () => T[K]) { +export default function (object: T, path: K, value: any) { if (object === undefined || path === undefined) throw new Error('should not be undefined') + return { - run(ctx: {stubs: any[]}) { - ctx.stubs = ctx.stubs || [] - const descriptor = Object.getOwnPropertyDescriptor(object, path) - if (descriptor && descriptor.get) { - ctx.stubs.push(descriptor.get) - descriptor.get = value - Object.defineProperty(object, path, descriptor) - } else { - ctx.stubs.push(_.get(object, path)) - _.set(object, path, value) - } - }, finally(ctx: {stubs: any[]}) { - const stub = ctx.stubs.pop() - const descriptor = Object.getOwnPropertyDescriptor(object, path) - if (descriptor && descriptor.get) { - descriptor.get = stub - Object.defineProperty(object, path, descriptor) - } else { - _.set(object, path, stub) - } + run(ctx: {sandbox: any}) { + const sandbox = ctx.sandbox = ctx.sandbox || sinon.createSandbox() + sandbox.stub(object, path).value(value) + }, finally(ctx: {sandbox: any}) { + ctx.sandbox.restore() }, } } diff --git a/test/stub.test.ts b/test/stub.test.ts index 14f5be0..be51f2e 100644 --- a/test/stub.test.ts +++ b/test/stub.test.ts @@ -38,7 +38,7 @@ describe('stub', () => { fancy .stdout() - .stub(mrGetter, 'foo', () => 2) + .stub(mrGetter, 'foo', 2) .end('resets getter', output => { console.log(mrGetter.foo) expect(output.stdout).to.equal('2\n')