首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用Nock测试请求错误?

如何用Nock测试请求错误?
EN

Stack Overflow用户
提问于 2014-12-30 16:27:11
回答 4查看 19.6K关注 0票数 23

我想测试请求返回中的错误。我在测试中使用了nock,我如何才能强迫Nock引发错误呢?我想达到100%的测试覆盖率,并且需要测试错误分支。

代码语言:javascript
复制
request('/foo', function(err, res) {
  if(err) console.log('boom!');
});

永远不要进入错误分支。即使命中错误是有效的响应,测试中的Nock行看起来也是这样

代码语言:javascript
复制
nock('http://localhost:3000').get('/foo').reply(400);

编辑:感谢一些评论:

  • 我试图模拟请求中的一个错误。节点手册:callback如果在请求过程中遇到任何错误(无论是使用DNS解析、TCP级别的错误还是实际的HTTP解析错误),将在返回的请求对象上发出一个“error”事件。
  • 错误代码(例如,4xx)不定义err变量。我试图准确地嘲笑这个错误,不管是什么错误定义了错误变量并计算为true。
EN

回答 4

Stack Overflow用户

发布于 2015-05-06 07:09:55

使用replyWithError。从医生那里:

代码语言:javascript
复制
    nock('http://www.google.com')
   .get('/cat-poems')
   .replyWithError('something awful happened');
票数 43
EN

Stack Overflow用户

发布于 2015-01-04 12:04:51

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

只要您能够得到这个对象(这可能需要一些重构,或者它可能不适合您),您就可以让这个发射器发出一个error事件,从而触发回调,err是您发出的错误。

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

代码语言:javascript
复制
'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的本机模块被缓存并在整个应用程序中重用这一事实,因此我们可以修改http模块,请求将看到我们的修改。诀窍在于猴子修补http.request()方法,并将我们自己的逻辑注入其中。

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

代码语言:javascript
复制
'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会做类似的事情(替换http模块上的方法),所以我建议您在之后应用这个猴子补丁程序(可能还配置了?)诺克。

请注意,您的任务是确保只在请求正确的URL (检查opts对象)时发出错误,并恢复原始的http.request()实现,以便以后的测试不受更改的影响。

票数 5
EN

Stack Overflow用户

发布于 2020-09-22 14:43:55

发布使用nockrequest-promise的更新答案。

让我们假设您的代码像这样调用request-promise

代码语言:javascript
复制
require('request-promise')
  .get({
    url: 'https://google.com/'
  })
  .catch(res => {
    console.error(res);
  });

您可以像这样设置nock来模拟500个错误:

代码语言:javascript
复制
nock('https://google.com')
  .get('/')
  .reply(500, 'FAILED!');

catch块将记录一个StatusCodeError对象:

代码语言:javascript
复制
{
  name: 'StatusCodeError',
  statusCode: 500,
  message: '500 - "FAILED!"',
  error: 'FAILED!',
  options: {...},
  response: {
    body: 'FAILED!',
    ...
  }
}

然后,您的测试可以验证该错误对象。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27708960

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档