我想测试请求返回中的错误。我在测试中使用了nock,我如何才能强迫Nock引发错误呢?我想达到100%的测试覆盖率,并且需要测试错误分支。
request('/foo', function(err, res) {
if(err) console.log('boom!');
});永远不要进入错误分支。即使命中错误是有效的响应,测试中的Nock行看起来也是这样
nock('http://localhost:3000').get('/foo').reply(400);编辑:感谢一些评论:
发布于 2015-05-06 07:09:55
使用replyWithError。从医生那里:
nock('http://www.google.com')
.get('/cat-poems')
.replyWithError('something awful happened');发布于 2015-01-04 12:04:51
使用request(url, callback)初始化http(s)请求时,它将返回事件发射器实例(以及一些自定义属性/方法)。
只要您能够得到这个对象(这可能需要一些重构,或者它可能不适合您),您就可以让这个发射器发出一个error事件,从而触发回调,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的本机模块被缓存并在整个应用程序中重用这一事实,因此我们可以修改http模块,请求将看到我们的修改。诀窍在于猴子修补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会做类似的事情(替换http模块上的方法),所以我建议您在之后应用这个猴子补丁程序(可能还配置了?)诺克。
请注意,您的任务是确保只在请求正确的URL (检查opts对象)时发出错误,并恢复原始的http.request()实现,以便以后的测试不受更改的影响。
发布于 2020-09-22 14:43:55
发布使用nock和request-promise的更新答案。
让我们假设您的代码像这样调用request-promise:
require('request-promise')
.get({
url: 'https://google.com/'
})
.catch(res => {
console.error(res);
});您可以像这样设置nock来模拟500个错误:
nock('https://google.com')
.get('/')
.reply(500, 'FAILED!');catch块将记录一个StatusCodeError对象:
{
name: 'StatusCodeError',
statusCode: 500,
message: '500 - "FAILED!"',
error: 'FAILED!',
options: {...},
response: {
body: 'FAILED!',
...
}
}然后,您的测试可以验证该错误对象。
https://stackoverflow.com/questions/27708960
复制相似问题