Skip to content

Instantly share code, notes, and snippets.

@eschwartz
Last active April 12, 2016 15:28
Show Gist options
  • Save eschwartz/d7d2543513e487475c2ae08a95f9b9db to your computer and use it in GitHub Desktop.
Save eschwartz/d7d2543513e487475c2ae08a95f9b9db to your computer and use it in GitHub Desktop.
Using deferred to test async services
function mockReadFile(mockPath, content) {
// see https://gist.github.com/eschwartz/955a3f8925e24270550cb635dd49c12b
const deferred = Deferred();
sinon.stub(fs, 'readFile', _.wrap(fs.readFile, (origFn, path, encoding, cb) => {
if (path !== mockPath) {
return origFn.readFile(path, encoding, cb);
}
// Only resolve `fs.readFile` when deferred is resolved
deferred.promise.then(() => cb(null, content));
});
return deferred;
}
it('should wait to resolve readFile', () => {
const deferred = mockReadFile('file.txt', 'fileContent');
fs.readFile('file.txt', 'utf8', (err, content) => {
console.log(`file.txt contains '${content}'`);
});
// ....
// Resolve the deferred, allowing fs.readFile to complete
deferred.resolve();
// "file.txt contains 'file content'"
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment