Skip to content

Instantly share code, notes, and snippets.

@mathieueveillard
Created February 22, 2023 09:34
Show Gist options
  • Save mathieueveillard/5b189aac349f62dae0a6402753a6d539 to your computer and use it in GitHub Desktop.
Save mathieueveillard/5b189aac349f62dae0a6402753a6d539 to your computer and use it in GitHub Desktop.
Jest mock
export const createMock = <T>(values: T[] = []) => {
function* generator(): Generator<T, T | undefined, T> {
for (let i = 0; i < values.length; i++) {
yield values[i];
}
return undefined;
}
const generatorInstance = generator();
const mockingFunction = (): T | undefined => {
const a = generatorInstance.next();
return a.value;
};
mockingFunction.returnValueOnce = (value: T) => {
return createMock([...values, value]);
};
return mockingFunction;
};
const mock = createMock().returnValueOnce(100).returnValueOnce(10);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment