Created
December 13, 2015 09:01
-
-
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
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
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 | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Do you have a working example? I like your setup a lot.