Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js Nock simulate request timeout and subsequent success

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');
like image 355
ejfrancis Avatar asked Jul 21 '15 19:07

ejfrancis


1 Answers

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)

like image 181
ejfrancis Avatar answered Oct 22 '22 04:10

ejfrancis