Skip to content

Instantly share code, notes, and snippets.

@mantoni
Created February 28, 2018 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mantoni/00ff8e30e0404bf57a4164910c53bf58 to your computer and use it in GitHub Desktop.
Save mantoni/00ff8e30e0404bf57a4164910c53bf58 to your computer and use it in GitHub Desktop.
SInon yields demo
'use strict';
const fs = require('fs');
exports.readJsonFile = function (file, callback) {
fs.readFile(file, 'utf8', (err, content) => {
if (err) {
callback(err);
return;
}
let json;
try {
json = JSON.parse(content);
} catch (e) {
callback(e);
return;
}
callback(null, json);
});
};
{
"name": "sinon-yields-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "mocha test.js",
"watch": "mocha test.js --watch"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"mocha": "^5.0.1",
"sinon": "^4.4.2"
}
}
/*eslint-env mocha*/
'use strict';
const assert = require('assert');
const sinon = require('sinon');
const fs = require('fs');
const api = require('./');
describe('readJsonFile', () => {
const sandbox = sinon.createSandbox();
beforeEach(() => {
sandbox.stub(fs, 'readFile');
});
afterEach(() => {
sandbox.restore();
});
it('calls fs.readFile with utf8 encoding', () => {
api.readJsonFile('some-file.json', () => {});
sinon.assert.calledWith(fs.readFile, 'some-file.json', 'utf8');
});
it('yields parsed file content', () => {
fs.readFile.yields(null, '{"some":"json"}');
const callback = sinon.spy();
api.readJsonFile('x.json', callback);
sinon.assert.calledWith(callback, null, { some: 'json' });
});
it('yields error from readFile', () => {
const error = new Error('Oh noes!');
fs.readFile.yields(error);
const callback = sinon.spy();
api.readJsonFile('x.json', callback);
sinon.assert.calledWith(callback, error);
});
it('yields error from JSON.parse', () => {
fs.readFile.yields(null, '{"some":invalid json}');
const callback = sinon.spy();
api.readJsonFile('x.json', callback);
sinon.assert.calledWithMatch(callback, { name: 'SyntaxError' });
});
it('does not yield error thrown by callback', () => {
fs.readFile.yields(null, '{"some":"json"}');
const callback = sinon.spy((err, content) => {
if (content) {
throw new Error('Oups!');
}
})
assert.throws(() => {
api.readJsonFile('x.json', callback);
}, /Error: Oups!/);
sinon.assert.calledOnce(callback);
sinon.assert.calledWith(callback, null, { some: 'json' });
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment