Back to Nock

Analysis of lifecycle methods (RFC-001)

rfcs/rfc-001.md

15.0.04.7 KB
Original Source

Analysis of lifecycle methods (RFC-001)

In Nock v10/v11, the lifecycle methods are confusingly named, difficult to understand, and at times inconvenient. Unless they are studied carefully, it is easy to inadvertently leave unwanted state in Nock.

Nock doesn't automatically provide a way to assert that mocks have been satisfied; it's the caller's responsibility to do this for each mock.

This RFC analyzes the most common use cases and the function calls currently needed for each one. Subsequent RFCs will propose changes to the lifecycle APIs which better afford these use cases.

See https://github.com/paulmelnikow/icedfrisby-nock/blob/8bdb5cbc9f6ec38bcdd8d1ec6f8979b05ab6a905/icedfrisby-nock.js for an attempt at getting the lifecycle right.

Typical use cases

  1. Assert that all mocks have been satisfied.
  2. Completely reset Nock after a test.
  3. Allow unmocked requests only to certain hosts.
  4. Prevent unmocked requests entirely.
  5. Simulate network connection failures.
  6. Temporarily disable http call interception while preserving registered mocks.
  7. Turn Nock all the way off and clean up its state. (I haven't experienced a need for this, but wanted to include it in the analysis.)

Analysis

Use caseCodeAssessment
Assert that all mocks have been satisfiedscopes.forEach(scope => scope.done()). When using nockBack, assert.deepEqual(scope.pendingMocks(), [])done() could have a more explicit name, though otherwise this is fairly clear. However it requires the caller to keep track of all the scopes, which is not ideal.
Reset Nock after a test to its initial post-require() statenock.restore(); nock.cleanAll(); nock.enableNetConnect(); nock.activate()This is a lot of typing. Some developers may wish to abort response playback that is in flight. (#1118)
Forbid unmocked requestsnock.disableNetConnect()This looks okay, but it doesn't have the desired effect. Errors are received by the client code and often swallowed up by the application (#884).
Allow unmocked requests, but only to certain hostsnock.disableNetConnect(); nock.enableNetConnect('example.com')This is a common use case, and should be possible to do more succintly, with a single call.
Simulate network connection failureN/AThis is what disableNetConnect() does today. However from the function name, it's not really clear this is the intention.
Temporarily disable http interception while preserving registered mocksnock.restore()This is a confusing name, as it only cleans part of nock's state.
Turn Nock all the way off and clean up its statenock.restore(); nock.cleanAll()restore() is a confusing name. This isn't the most common use case, so it is probably okay that it requires two function calls.

References