Created
September 7, 2018 07:28
-
-
Save devarajchidambaram/bf05d68116bc6261add765e162deaac2 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
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.