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');
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With