模拟一个HEAD请求redirect(通过nock模块)

在我的项目中,我尝试扩展推文以充分显示。 由bit.ly缩短的链接被这个和平的代码扩展(find@ stackoverflow)。

function expandUrl(shortUrl,callback) { debug("expandUrl"); request( { method: "HEAD", url: shortUrl, followAllRedirects: true }, function (error, response) { if (error) return callback(null,shortUrl); return callback(null,response.request.href); } ); } 

在摩卡testing期间不需要在线,我想用下面的代码来禁止这部分代码:

 nock('http://bit.ly') .intercept("/1Ghc7dI","HEAD") .reply(200,undefined,{location:"http://discoverspatial.com/courses/qgis-for-beginners"}); 

但是这不起作用。 这个工作后,response.request.href是“undefined”。 (我试过href而不是位置,这没有什么区别。

为了提供redirect,您需要将状态设置为HTTP URLredirect状态,如@apsillers在注释中所述。 此外,如果您不想上线,则还需要locking目标url,因为请求会调用它来检查它不是redirect:

 nock('http://bit.ly') .intercept("/1Ghc7dI","HEAD") .reply(301,undefined,{location:"http://discoverspatial.com/courses/qgis-for-beginners"}); nock('http://discoverspatial.com') .intercept("/courses/qgis-for-beginners", "HEAD") .reply(200,"OK");