Created
November 18, 2015 18:00
-
-
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
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
// 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