Skip to content

Instantly share code, notes, and snippets.

@devarajchidambaram
Created September 7, 2018 07:28
Show Gist options
  • Save devarajchidambaram/bf05d68116bc6261add765e162deaac2 to your computer and use it in GitHub Desktop.
Save devarajchidambaram/bf05d68116bc6261add765e162deaac2 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')
})
})
@SorinaAvram
Copy link

Hey, what if i have a simple function getFile(path) that returns the file,
and i want to test fs.readFileSync where it throws an error?
What I have is :

it('should throw an error id fs.readFileSync throws an error', () => {
const error = new Error("some err message")
const stub = sinon.stub(fs, readFileSync)
stub.throws(error)
)}

try {
stub ();
} catch (error) {
expect(stub).to.throw(error)

the test passes, but it does not print the error message, does not seem to execute the code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment