Skip to content
This repository has been archived by the owner on May 22, 2024. It is now read-only.

Replace custom stubbing with sinon #30

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 8 additions & 22 deletions src/stub.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,17 @@
import * as _ from 'lodash'
import * as sinon from 'sinon'

/**
* mocks an object's property
*/
export default function<T extends object, K extends keyof T> (object: T, path: K, value: () => T[K]) {
export default function<T extends object, K extends keyof T> (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()
},
}
}
2 changes: 1 addition & 1 deletion test/stub.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down