Skip to content

Instantly share code, notes, and snippets.

@mhaylock
Last active January 17, 2020 10:49
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 mhaylock/df78ab73b6788fe49e000e09cff55252 to your computer and use it in GitHub Desktop.
Save mhaylock/df78ab73b6788fe49e000e09cff55252 to your computer and use it in GitHub Desktop.
Integrating Nock with Jest
const nock = require('nock')
// Prevent requests being made to any outside services:
nock.disableNetConnect()
// Allow requests through to localhost, which is used by SuperTest to send
// requests during integration tests:
const localhost = '127.0.0.1'
nock.enableNetConnect(localhost)
let unmockedRequest
beforeEach(() => {
unmockedRequest = null
// Clean up any unfulfilled mocked requests from the previous test run (these
// may exist if the previous test failed):
nock.cleanAll()
})
afterEach(() => {
// Raise an error if an unmocked request was encountered during the test.
//
// This is helpful when application code might be swallowing the
// `NetConnectNotAllowedError` that Nock generates meaning that the cause of
// the failure will not be obvious without debugging the application.
if (unmockedRequest) {
const { method, protocol, hostname, path } = unmockedRequest
const url = `${protocol}//${hostname}${path}`
const formattedMethod = method ? ` ${method.toUpperCase()} ` : ' '
// Throwing a string avoids this error including a stack trace which would
// point to this code rather than the origin of the unmocked request (the
// test itself should have failed at the point where Nock raised it's
// `NetConnectNotAllowedError`):
throw `Test included unmocked${formattedMethod}request to "${url}"`
}
// Raise an error if any mocked requests were not received as expected:
if (!nock.isDone()) {
throw `Some mocked requests were not received as expected: ${nock
.pendingMocks()
.join(', ')}`
}
})
// Capture any unmocked request, so that an error can be raised after the test.
//
// Nock itself will raise an error at the point where these requests were made,
// but exposing them directly solves for the problem of the application code
// hiding the details of the error from Nock.
nock.emitter.on('no match', request => {
if (request.hostname !== localhost) {
unmockedRequest = request
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment