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
19 changes: 19 additions & 0 deletions packages/spy/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ 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(fn: ((...args: TArgs) => TReturns), cb: () => void): this
sheremet-va marked this conversation as resolved.
Show resolved Hide resolved
mockReturnThis(): this
mockReturnValue(obj: TReturns): this
mockReturnValueOnce(obj: TReturns): this
Expand Down Expand Up @@ -248,6 +249,24 @@ function enhanceSpy<TArgs extends any[], TReturns>(
return stub
}

stub.withImplementation = (fn, cb) => {
const originalImplementation = implementation!
stub.mockImplementation(fn)

if (cb.constructor.name === 'AsyncFunction') {
sheremet-va marked this conversation as resolved.
Show resolved Hide resolved
const asyncCb = cb as () => Promise<void>

asyncCb().then(() => {
stub.mockImplementation(originalImplementation)
})
}
else {
sheremet-va marked this conversation as resolved.
Show resolved Hide resolved
stub.mockImplementation(originalImplementation)
}

return stub
}

stub.mockReturnThis = () =>
stub.mockImplementation(function (this: TReturns) {
return this
Expand Down