Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(spy): implement mock.withImplementation API #2835

Merged
merged 8 commits into from
Feb 24, 2023
34 changes: 33 additions & 1 deletion packages/spy/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ export interface SpyInstance<TArgs extends any[] = any[], TReturns = any> {
getMockImplementation(): ((...args: TArgs) => TReturns) | undefined
mockImplementation(fn: ((...args: TArgs) => TReturns) | (() => Promise<TReturns>)): this
mockImplementationOnce(fn: ((...args: TArgs) => TReturns) | (() => Promise<TReturns>)): this
withImplementation<T>(fn: ((...args: TArgs) => T), cb: () => void): this
withImplementation<T>(fn: ((...args: TArgs) => T), cb: () => Promise<void>): Promise<this>
mockReturnThis(): this
mockReturnValue(obj: TReturns): this
mockReturnValueOnce(obj: TReturns): this
Expand Down Expand Up @@ -208,6 +210,7 @@ function enhanceSpy<TArgs extends any[], TReturns>(
}

let onceImplementations: ((...args: TArgs) => TReturns)[] = []
let implementationChangedTemporarily = false

let name: string = (stub as any).name

Expand Down Expand Up @@ -248,6 +251,35 @@ function enhanceSpy<TArgs extends any[], TReturns>(
return stub
}

function withImplementation(fn: (...args: TArgs) => TReturns, cb: () => void): EnhancedSpy<TArgs, TReturns>
function withImplementation(fn: (...args: TArgs) => TReturns, cb: () => Promise<void>): Promise<EnhancedSpy<TArgs, TReturns>>
function withImplementation(fn: (...args: TArgs) => TReturns, cb: () => void | Promise<void>): EnhancedSpy<TArgs, TReturns> | Promise<EnhancedSpy<TArgs, TReturns>> {
const originalImplementation = implementation!

stub.mockImplementation(fn)
implementationChangedTemporarily = true

const clean = () => {
stub.mockImplementation(originalImplementation)
implementationChangedTemporarily = false
}

const result = cb()

if (result instanceof Promise) {
return result.then(() => {
clean()
return stub
})
}

clean()

return stub
}

stub.withImplementation = withImplementation

stub.mockReturnThis = () =>
stub.mockImplementation(function (this: TReturns) {
return this
Expand Down Expand Up @@ -275,7 +307,7 @@ function enhanceSpy<TArgs extends any[], TReturns>(
stub.willCall(function (this: unknown, ...args) {
instances.push(this)
invocations.push(++callOrder)
const impl = onceImplementations.shift() || implementation || stub.getOriginal() || (() => {})
const impl = implementationChangedTemporarily ? implementation! : onceImplementations.shift() || implementation || stub.getOriginal() || (() => {})
return impl.apply(this, args)
})

Expand Down