Skip to content

Instantly share code, notes, and snippets.

@LoganBarnett
Created November 18, 2015 18:00
Show Gist options
  • Save LoganBarnett/3adbceb06e323c11e3eb to your computer and use it in GitHub Desktop.
Save LoganBarnett/3adbceb06e323c11e3eb to your computer and use it in GitHub Desktop.
Showing how you can use higher order functions to remove the need for mocks
// the way you'd normally think to do it. This requires mocking out writeFileSync to test
var fs = require('fs');
function writeXmlToFile(fileName, data) {
// do stuff with data
// make data into xml
var xml = toXml(data);
fs.writeFileSync(fileName, {encoding: 'utf-8'}, xml);
}
// with higher order functions, a mock isn't necessary to test
// 'writeXmlToFile' doesn't make sense anymore
function writeXmlData(writeFn, data) {
var xml = toXml(data);
writeFn(data); // external interface just got super simple
}
// usage:
var fs = require('fs');
// underscore, lodash, ramda, or whatever for your flavor of partial application
var writeFn = _.partial(fs.writeFileSync, fileName, {encoding: 'utf-8'});
writeXmlData(writeFn, data);
// testing:
var spy = jasmine.createSpy('writeFile');
writeXmlData(spy, data);
expect(spy).toHaveBeenCalledWith('<xml... ');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment