disableNetConnect() / "Not allow net connect" errors are swallowed up
See original GitHub issueI’m testing the API for shields, which is a server that sits in front of a bunch of third-party APIs. I wrote a plugin that integrates Nock into an API testing framework. Overall it’s been fun and is working well!
I did encounter a surprising behavior which was tricky to debug. When I have disabled network connections, if my application makes a request, I want my tests to fail with an error about the unexpected request.
The observed behavior is that the error is passed to the application like any other network error. It gets processed by the application’s error-handling code, as if it were an ECONNREFUSED
or ECONNRESET
. In other words, Nock simulates the effect of network errors.
The expected behavior is that the error bubble up as an unhandled exception, to be caught by the test runner. By throwing an exception, Nock is saying, “you asked me not to allow unexpected network connections, but then you made one.” You’re on lockdown. Nock forbids unexpected connections.
I can get nearly the behavior I want by calling scope.done()
after my tests, though the error message is opaque, and doesn’t make it clear an unauthorized request was rejected.
Nock tests are often tricky to write, requiring trial and error. Until they are correct, they fail silently, because everything has to be perfect for the request to match. And if I’m doing TDD, I don’t know if the test or the application is at fault. Throwing the error at the time of the unauthorized connection would make this more transparent.
This odd issue tends to come up because I’m using mostly live requests. I’m using mocks to cover the error-handling paths which are impossible to test with live requests, including the path that handles connection errors. When the error is swallowed up, it’s particularly baffling.
I can see use cases, even in Shields, where a dev wants to simulate network errors, though the “lockdown” behavior would seem a clearer default.
The documentation reads:
The returned
http.ClientRequest
will emit an error event (or throw if you’re not listening for it)
In practice, anyone using a wrapper like request
will see an error, not a thrown exception.
Issue Analytics
- State:
- Created 6 years ago
- Reactions:7
- Comments:8 (2 by maintainers)
Sounds similar to what I experience. My app handles the errors thrown by nock, but I’d like my spec to fail. I would like to be able to ask
nock
if there were unmatched requests during the spec, similar to how you can ask if there are still pending mocks, e.g.:For now, I’ve solved it like this in my spec:
It would be nice if this
unmatchedRequests
method would also considernock.enableNetConnect('127.0.0.1');
. Now I have to filter myself on theno match
event.@mastermatt see #2211