如何用Nock请求testing错误?

我想在请求返回中testing错误。 我在testing中使用诺克,我怎么能强迫诺克挑起一个错误? 我想要达到100%的testing覆盖率,并且需要为此testingerr分支

request('/foo', function(err, res) { if(err) console.log('boom!'); }); 

切勿进入if er分支。 即使命中错误是一个有效的回应,我的诺克线testing看起来像这样

 nock('http://localhost:3000').get('/foo').reply(400); 

编辑:多谢一些意见:

  • 我试图嘲笑请求中的错误。 从节点手册: https : //nodejs.org/api/http.html#http_http_request_options_callback 如果在请求过程中遇到任何错误(包括DNSparsing,TCP级错误或实际的HTTPparsing错误),则“错误”事件是在返回的请求对象上发射
  • 错误代码(例如4xx)不会定义errvariables。 我试图嘲笑这一点,无论错误,定义errvariables和评估为真

使用replyWithError。 从文档:

  nock('http://www.google.com') .get('/cat-poems') .replyWithError('something awful happened'); 

当用request(url, callback)初始化一个http请求时,它将返回一个事件发射器实例(以及一些自定义属性/方法)。

只要你能掌握这个对象(这可能需要一些重构,或者它可能不适合你),你可以让这个发射器发出一个error事件,从而触发你的callback, err是你发出的错误。

下面的代码片段演示了这一点。

 'use strict'; // Just importing the module var request = require('request') // google is now an event emitter that we can emit from! , google = request('http://google.com', function (err, res) { console.log(err) // Guess what this will be...? }) // In the next tick, make the emitter emit an error event // which will trigger the above callback with err being // our Error object. process.nextTick(function () { google.emit('error', new Error('test')) }) 

编辑

这种方法的问题是,在大多数情况下,它需要一些重构。 另一种方法利用了Node的本地模块在整个应用程序中被caching和重用的事实,因此我们可以修改http模块, Request将会看到我们的修改。 诀窍在于修补http.request()方法,并将自己的逻辑注入到它中。

下面的代码片段演示了这一点。

 'use strict'; // Just importing the module var request = require('request') , http = require('http') , httpRequest = http.request // Monkey-patch the http.request method with // our implementation http.request = function (opts, cb) { console.log('ping'); // Call the original implementation of http.request() var req = httpRequest(opts, cb) // In next tick, simulate an error in the http module process.nextTick(function () { req.emit('error', new Error('you shall not pass!')) // Prevent Request from waiting for // this request to finish req.removeAllListeners('response') // Properly close the current request req.end() }) // We must return this value to keep it // consistent with original implementation return req } request('http://google.com', function (err) { console.log(err) // Guess what this will be...? }) 

我怀疑Nock做了类似的事情(replacehttp模块上的方法),所以我build议你在需要(也可能还configuration了?) Nock 应用这个猴子补丁。

请注意,只有在请求了正确的URL(检查opts对象)时,才能确保发出错误,并恢复原始的http.request()实现,以便将来的testing不会受到更改的影响。

看起来你正在寻找一个nock请求的exception,这可能会帮助你:

 var nock = require('nock'); var google = nock('http://google.com') .get('/') .reply(200, 'Hello from Google!'); try{ google.done(); } catch (e) { console.log('boom! -> ' + e); // pass exception object to error handler }