Matthew Herbst
Matthew Herbst

Reputation: 31993

How to get the name of a request via Nock object

At the point in my test code where I check assert that all nocks have been called, I have a semi-useful error message to dumps out if a nock wasn't called (since the default error message is useless):

try {
  assertions(data, result);
  if (assertNock !== null) {
    // Expect that all mocked calls were made
    if (nock.isDone() !== !!assertNock) {
      console.error('One or more of your Nock matchers was never called.');
    }
    expect(nock.isDone()).toBe(!!assertNock);
  }
  done();
} catch (err) {
  ...
}

However, I'd like to be able to specify which call wasn't made. But, I can't seem to find a way to get that information from the nock object, which looks like:

{ [Function: startScope]
  emitter:
   EventEmitter {
     domain: null,
     _events: {},
     _eventsCount: 0,
     _maxListeners: undefined },
  define: [Function: define],
  loadDefs: [Function: loadDefs],
  load: [Function: load],
  enableNetConnect: [Function: enableNetConnect],
  disableNetConnect: [Function: disableNetConnect],
  removeInterceptor: [Function: removeInterceptor],
  activeMocks: [Function: activeMocks],
  pendingMocks: [Function: pendingMocks],
  isDone: [Function: isDone],
  isActive: [Function: isActive],
  activate: [Function: activate],
  cleanAll: [Function: cleanAll],
  recorder:
   { rec: [Function: record],
     clear: [Function: clear],
     play: [Function] },
  back: { [Function: Back] setMode: [Function], fixtures: null, currentMode: 'dryrun' },
  restore: [Function: restore]
}

How can I get useful/identifying information about the request that was't made from the nock object?

Upvotes: 0

Views: 208

Answers (1)

openam
openam

Reputation: 71

As per the documentation, interceptors are removed once they have been called. With that knowledge, one can then use nock.activeMocks() which will return an array of items that are still active. If you have added .persist() to any of the nocks they will still be in the list. In that case you may want to use nock.pendingMocks() which will only return the nocks that haven't yet been called.

    nock.activeMocks(); // [ 'GET https://www.example.com:443/fake/url', 'POST https://sts.amazonaws.com:443/' ]
    nock.pendingMocks(); // [ 'GET https://www.example.com:443/fake/url' ]

Upvotes: 2

Related Questions