Skip to content

Instantly share code, notes, and snippets.

@cefn
Created August 19, 2022 01:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cefn/e5ae3d6d330e85a84238af657726e504 to your computer and use it in GitHub Desktop.
Save cefn/e5ae3d6d330e85a84238af657726e504 to your computer and use it in GitHub Desktop.
Create a jest mock function which is awaitable
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