How to await until nock is called

1.9k Views Asked by At

I'm not sure if nock is supporting awaiting or notifying using callback / event-emitter when the interceptor is called.

For example:

const scope = nock(config.research.url)
                   .post(config.research.routes.getOdds, expectBody)
                   .reply(200)

while(true){
  expect(scope.isDone()).toBeTruthy()
  await sleep(500)
}

My Question

How can I improve the above code using nock API?

2

There are 2 best solutions below

0
On BEST ANSWER

nock emits event on request and response: https://github.com/nock/nock/#events

emit('request', function(req, interceptor, body))
emit('replied', function(req, interceptor))

Your code can listen to the replied event to get notified.

0
On

nock allows to pass a callback to the reply function this can be one of the ways to handle that. Wrap your reply code into a Promise and wait for it.

Another solution could be to subscribe to the replied event that scope emits and wrap it into a Promise to wait for a reply

 scope.on('replied', function(req, interceptor) { ... })