gpt4 book ai didi

javascript - 如何使用诺克和请求库进行 ETIMEDOUT

转载 作者:搜寻专家 更新时间:2023-10-31 23:46:56 28 4
gpt4 key购买 nike

如何使用 nock ( https://github.com/node-nock/nock ) 和 request 强制执行 ETIMEDOUT?
我尝试了以下方法,其中 nock 会延迟响应 8000 毫秒,而请求超时将设置为 5000 毫秒,所以我希望看到 ETIMEDOUT 但事实并非如此。代码将返回 然后 block 不应执行:来自 Google 的问候!

摩卡测试/force-req-timeout.test.js --timeout=10000

'use strict'

const expect = require('chai').expect
const nock = require('nock')
const rp = require('request-promise')

describe('force request timeout with nock', () => {
it('should return ETIMEDOUT', (done) => {

nock('http://www.google.com')
.get('/')
.delay(8000)
.reply(200, 'Hello from Google!')

rp({
url: 'http://www.google.com',
timeout: 5000
})
.then((data) => {
console.log('then block should not execute: ', data)
})
.catch((err) => {
expect(err.cause.code).to.equal('ETIMEDOUT')
return done()
})
})
})

最佳答案

最后我解决了这个问题:

nock('http://www.google.com')
.get('/')
.replyWithError({code: 'ETIMEDOUT'})

看起来很干净,它不涉及 delay 之类的东西,而且在我看来模拟 ETIMEDOUT 就足够了,记住我正在使用request-promise 库,其中我正在检查 ETIMEDOUT,例如:if (err.error && err.error.code === 'ETIMEDOUT')

关于javascript - 如何使用诺克和请求库进行 ETIMEDOUT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36533807/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com