From 40b3d93fd26777d3a33471bc076caa198bf98212 Mon Sep 17 00:00:00 2001 From: unional Date: Sun, 7 Jan 2018 22:46:07 -0800 Subject: [PATCH] chore: add kotlin folder --- kotlin/spy.kt | 71 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 kotlin/spy.kt diff --git a/kotlin/spy.kt b/kotlin/spy.kt new file mode 100644 index 0000000..40d6eb2 --- /dev/null +++ b/kotlin/spy.kt @@ -0,0 +1,71 @@ +package spy +interface Error { + var name: String + var message: String +} +interface CallRecord { + var arguments: Array + var result: Any + var error: Error +} + +interface Spy { + var calls: Array +} + +/** + * Spy on function that uses callback. + */ +fun spy(fn: T): T & Spy { + const calls: CallRecord[] = [] + const spiedFn: T = function (...args) { + const spiedArgs = args.map(a => { + return typeof a === 'function' ? spy(a) : a + }) + const call = { arguments: spiedArgs } as CallRecord + calls.push(call) + try { + const result = fn(...spiedArgs) + call.result = result + return result + } + catch (err) { + call.error = err + throw err + } + } as any + + return Object.assign(spiedFn, { + calls + }) +} + + +interface AsyncCallRecord extends Promise { + arguments: any[], + throws(errback: any): Promise +} + +interface AsyncSpy { + calls: ReadonlyArray +} + +/** + * Spy on function that returns a promise. + */ +fun spyAsync(fn: T): T & AsyncSpy { + const calls: AsyncCallRecord[] = [] + const spiedFn: T = function (...args) { + const call = { arguments: args } as AsyncCallRecord + calls.push(call) + const result = fn(...args) + call.then = (cb, eb) => result.then(cb, eb) + call.catch = cb => (result.catch(cb)) + call.throws = call.catch + return result + } as any + + return Object.assign(spiedFn, { + calls + }) +}