【问题标题】:Nock isn't matching HTTPS call inside middleware?Nock 与中间件内部的 HTTPS 调用不匹配?
【发布时间】:2019-01-24 04:38:14
【问题描述】:

我有一个通过请求向第三方服务执行身份验证的中间件。我用 superagent 做这个请求。显然我想在我的测试中模拟它,因为它会减慢它们的速度,并且还依赖于第三方服务器。

使用 nock 时,似乎根本找不到请求。我什至尝试使用记录器,它只接收本地端点的实际请求。 (虽然它使用了不熟悉的 IP 和端口?)。

我的中间件里面的请求;

export default async (req, res, next) => {
      const user = await superagent
      .get(`https://example.com/session/`)
      .query({ session })
      .set('Api-Key', '1234');
}

我的诺克实例;

nock('https://example.com/session/')
  .persist()
  .get('/session/')
  .reply(200, {
    success: true,
    username: 'testuser',
  })
  .log(console.log);

【问题讨论】:

    标签: node.js jestjs nock


    【解决方案1】:

    这里有 2 个问题。

    首先,你定义了两次/session/

    • nock('https://example.com/session/')
    • .get('/session/')

    选择:

    • nock('https://example.com').get('/session/')
    • nock('https://example.com/session/').get('/')

    第二个问题,您在呼叫中添加了一个查询字符串 (.query({ session })),但您没有使用 .query(true) 告诉 Nock。

    最后,你应该有类似的东西:

    nock('https://example.com/session/')
      .persist()
      .get('/') // rewrote here
      .query(true) // added here
      .reply(200, {
        success: true,
        username: 'testuser',
      })
      .log(console.log);
    

    【讨论】:

      猜你喜欢
      • 2021-02-03
      • 2018-07-18
      • 1970-01-01
      • 2020-08-09
      • 2019-07-19
      • 2015-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多