-
-
Save alexaleluia12/3b5ef05984b0d04595a758b391ef5f11 to your computer and use it in GitHub Desktop.
How to stub fs.readFile functions
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
const fs = require('fs') | |
function readFile (filename) { | |
if (fs.existsSync(filename)) { | |
return fs.readFileSync(filename, 'utf8') | |
} | |
throw new Error('Cannot find file ' + filename) | |
} | |
describe('mocking individual fs sync methods', () => { | |
const sinon = require('sinon') | |
beforeEach(() => { | |
sinon.stub(fs, 'existsSync').withArgs('foo.txt').returns(true) | |
sinon | |
.stub(fs, 'readFileSync') | |
.withArgs('foo.txt', 'utf8') | |
.returns('fake text') | |
}) | |
afterEach(() => { | |
// restore individual methods | |
fs.existsSync.restore() | |
fs.readFileSync.restore() | |
}) | |
it('reads non-existent file', () => { | |
console.assert(readFile('foo.txt') === 'fake text') | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment