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');
4

1 回答 1

14

我会回答我自己的问题,因为我想通了。事实证明,nock 允许为同一端点排队模拟,尽管它不在文档中的任何地方。这是我用来模拟请求中不同延迟时间的方法。注意每个回复正文的不同值

 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');

使用requestretrytimeout=300、retryDelay=500 和 maxAttempts=2 的模块后,响应应该是自前两次超时后的第三次请求的主体。请注意,我为每个响应主体使用了不同的值,以确保我实际上在前两个响应中超时。您可以验证前两个请求是否失败,因为测试需要 1800 毫秒才能完成。300ms(第一次超时)+ 500ms(延迟)+ 300ms(第二次超时)+ 500ms(延迟)+ 200ms(成功请求)

于 2015-07-21T22:58:49.460 回答