【问题标题】:Mocking with nock. Mock only one path from the same host用诺克嘲讽。仅模拟来自同一主机的一条路径
【发布时间】:2018-04-25 11:59:30
【问题描述】:

我正在使用诺克。 我想知道我是否只能模拟对主机的一些调用,具体取决于路径。我正在使用 {allowUnmocked: true },它没有帮助。

例如,我只想模拟这些调用中的一个(数字是 id,所以我不知道全部):

这个问题和这个问题类似: Mocking with Nock, mock only a specific route with the same host

【问题讨论】:

    标签: node.js nock


    【解决方案1】:

    诺克拦截器only fire once

    你可以配置一个包罗万象的路径,像这样:

    nock('http://blabla.com').get(/account/) // if any path has 'account' in it, somewhere
    

    一旦该拦截器被捕获,nock 将不会捕获对该匹配 URL 的下一次调用。

    或者你可以指定一个特定的 ID,比如

    nock('http://blabla.com').get('/account/' + id)
    

    显然只有那个 ID 会被拦截,因为其他 ID 不会匹配模式。您也可以为每个回复做出不同的模拟回复。

    【讨论】:

    • 谢谢。我接受了这个并进行了更改,因此逻辑处于不同的功能中。文档对我来说不是很清楚。
    【解决方案2】:

    这就是我所做的。我想模拟所有在他们的路径中有 123456 的呼叫。所以,如果路径没有它,我返回 X,并且只获取那些不是 X 的(使用负前瞻正则表达式)

    nock(`https://my-url.com`, {
      allowUnmocked: true,
    })
    .filteringPath((thePath) => {
    const match = /123456/.test(thePath);
    return match ? thePath : 'X';
      })
    .persist()
    // This handles all request but 'X' (returned by the filteringPath fn).
    .get(/^(?!(?:X)$).*$/)
    

    【讨论】:

      猜你喜欢
      • 2015-01-07
      • 2019-05-28
      • 1970-01-01
      • 2017-11-20
      • 2018-05-27
      • 2019-06-12
      • 2014-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多