Created
August 19, 2022 01:35
-
-
Save cefn/e5ae3d6d330e85a84238af657726e504 to your computer and use it in GitHub Desktop.
Create a jest mock function which is awaitable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function waitableJestFn<Result, Args extends any[]>( | |
implementation?: (...args: Args) => Result, | |
) { | |
const mock = jest.fn<Result, Args>(implementation); | |
const asyncMethods = { | |
waitForCallback: (count = 1) => | |
new Promise<Args>((resolve) => { | |
mock.mockImplementation(((...args) => { | |
count--; | |
if (count === 0) resolve(args); | |
if (implementation) return implementation(...args); | |
}) as (...args: Args) => Result); | |
}), | |
} as const; | |
Object.assign(mock, asyncMethods); | |
return mock as typeof mock & typeof asyncMethods; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment