Skip to content

Instantly share code, notes, and snippets.

@nathanharper
Last active July 5, 2018 02:54
Show Gist options
  • Save nathanharper/d679c3aa5223736421e6 to your computer and use it in GitHub Desktop.
Save nathanharper/d679c3aa5223736421e6 to your computer and use it in GitHub Desktop.
Mock a promise object for jest tests
// Put this in your "setupEnvScriptFile" for Jest.
// usage: `jest.genMockFn().mockReturnValue(promisify('whateva'))`
promisify = function (returnValue, delay) {
delay = !!delay;
let delayCount = 0;
let recursiveMockPromise = new function () {
let self = this;
self.returnValue = returnValue;
self.then = (cb) => {
let performCallback = () => {
self.returnValue = cb(self.returnValue);
};
if (delay) {
setTimeout(performCallback, 1 + delayCount);
delayCount += 500;
} else {
performCallback();
}
return self;
};
self.catch = () => self;
return self;
};
return recursiveMockPromise;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment