Skip to content

Instantly share code, notes, and snippets.

@alexaleluia12
Forked from devarajchidambaram/stubfs.js
Created June 2, 2019 13:05
Show Gist options
  • Save alexaleluia12/3b5ef05984b0d04595a758b391ef5f11 to your computer and use it in GitHub Desktop.
Save alexaleluia12/3b5ef05984b0d04595a758b391ef5f11 to your computer and use it in GitHub Desktop.
How to stub fs.readFile functions
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