node.js - 使用 Nock 和 Request 模拟 HTTP 请求错误

标签 node.js mocking request

我在当前未测试的函数中有一个分支。它是来自 request 操作的错误处理程序(使用同名的 Node 模块)。这是特定的行:

request(url, function (error, response, body) {
  if (error) return cb(error);

这是测试:

  describe("handles errors", function() {
    it("from the request", function (done) {
    var api = nock('http://football-api.com')
                .get('/api/?Action=today&APIKey=' + secrets.APIKey + '&comp_id=1204')
                .reply(500);

    fixture.getFixture(FixtureMock, function (err, fixture) {
      expect(err).to.exist
      done();
    });
  });

规范失败:

Uncaught AssertionError: expected null to exist

因此,发送 500 状态代码作为没有正文的响应不会在请求回调中导致 error,或者我正在测试错误的东西。

最佳答案

使用文档中的replyWithError:

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

关于node.js - 使用 Nock 和 Request 模拟 HTTP 请求错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26248419/

相关文章:

javascript - Feathers调用自定义API方法

python - 获取模拟 file.read() 的实际返回值

node.js - Node JS 请求 + Express Pipe

javascript - ServiceWorker无故无法获取外部资源

javascript - 使用请求从 url 下载图像并保存到变量

node.js - 类型错误 : Cannot read property 'isTTY' of undefined

javascript - AWS.Comprehend 返回 405 'Method Not Allowed'

node.js - Node : Can I run global modules/packages from command line without specifying full path [Ubuntu, Nodejs,NPM]

Python:模拟的调用计数无法通过多处理并行执行

reactjs - Jest 模拟类型错误 : Cannot read property 'credential' of undefined on library react-native-firebase