Last active
April 12, 2016 15:28
-
-
Save eschwartz/d7d2543513e487475c2ae08a95f9b9db to your computer and use it in GitHub Desktop.
Using deferred to test async services
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 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