Node.js Nock模拟请求超时和后续成功

ejf*_*cis 7 javascript node.js nock

我正在尝试模拟服务请求超时以测试节点请求重试模块,该模块允许您指定请求最大尝试重试次数和重试延迟.为了测试这个,我需要使用nock来模拟前X个请求的超时,然后成功响应同一个请求.我知道有'socketDelay()'方法来延迟连接,但是如何在第一次延迟响应之后指定成功的响应?

我有这个,模拟第一个请求的超时

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

但是,如何在此之后更快地响应以模拟服务恢复?我希望沿着这些方向做点什么

//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');
Run Code Online (Sandbox Code Playgroud)

ejf*_*cis 10

自从我弄清楚之后,我会回答我自己的问题.事实证明,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');
Run Code Online (Sandbox Code Playgroud)

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