8

I'm trying to simulate service request timeouts to test the node requestretry module, which allows you to specify a request max # of attempted retries and retry delay. In order to test this, I need to use nock to simulate a timeout for the first X number of requests, then respond successfully to the same request. I know there is the 'socketDelay()' method to delay the connection, but how do I specify a successful response after that first delayed response?

I have this, which simulates a timeout on the first request

//delays the first request's response by 1500
nock(urlHost)
     .post('/' + uriPath)
     .socketDelay(1500)
     .reply(200, 'response body');

but how can I make it respond faster after that to simulate the service recovering? I'm looking to do something along these lines

//delays the first two request's responses by 1500
nock(urlHost)
    .post('/' + requestIdentifier.ttoRoutingInfo.uriPath)
    .socketDelay(1500)
    .reply(200, 'response body')
    .times(2)
  //delays the third request by only 300
    .then
    .socketDelay(300)
    .reply(200, 'response body');
ejfrancis
  • 2,465
  • 3
  • 22
  • 41

1 Answers1

13

I'll answer my own question since I figured it out. Turns out that nock allows for queueing mocks for the same endpoint, although it isn't anywhere in the documentation. This is what I used to simulate varied delay times in requests. Notice the different values for each reply body

 var nockScope = nock(urlHost)
        .post('/' + uriPath)
        .delayConnection(400)
        .reply(200, 'response body1')
        .post('/' + uriPath)
        .delayConnection(400)
        .reply(200, 'response body2')
        .post('/' + uriPath)
        .delayConnection(200)
        .reply(200, 'response body3');


 expect(data).to.equal('response body3');

After using the requestretry module with timeout=300, retryDelay=500 and maxAttempts=2, the response should be the body of the third request since the first two time out. notice that I used a different value for each response body to ensure I'm actually timing out on the first two. You can verify that the first two requests failed because the test took 1800ms to complete. 300ms(first timeout) + 500ms(delay) + 300ms(second timeout) + 500ms(delay) + 200ms(successful request)

ejfrancis
  • 2,465
  • 3
  • 22
  • 41
  • I've been trying this with more recent code and it seems that this doesn't work anymore. The last version I was on that worked was 11.7.2, but 11.8.0+ break it, somehow. Does this still work for you on recent versions? – Matej Voboril Feb 19 '21 at 23:41