Skip to content

Instantly share code, notes, and snippets.

@bigethan
Created December 13, 2015 09:01
Show Gist options
  • Save bigethan/aff817c913fa6a0cc217 to your computer and use it in GitHub Desktop.
Save bigethan/aff817c913fa6a0cc217 to your computer and use it in GitHub Desktop.
Nock and Proxyquire to easily mock code that makes API calls when testing
var nock = require('nock')
var proxyquire = require('proxyquire')
// get a refrence to the code that defines the external api call
var generateConfigForApiCall = require('../../../lib/api-config')
// data for testing
var mockData = require('../../mock-data')()
// require with proxyquire, and override the module that builds the api config
var runExternalApiCode = proxyquire('../../../tasks/run-external-api-code',
{'../lib/api-config': function (options) {
// run the module to get the right config
var psConfig = generateConfigForExternalCall(options)
// now that we have the config, use nock to intercept the coming http request
// and reply with the mock data
nock('https://' + psConfig.host)
.get(psConfig.path)
.reply(200, mockData)
// return the data as expected
return psConfig
}
})
@kwhitejr
Copy link

Do you have a working example? I like your setup a lot.

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