【问题标题】:Regex matching for nock tests failing诺克测试的正则表达式匹配失败
【发布时间】:2018-10-25 18:42:17
【问题描述】:

我正在尝试匹配 URL。

lab.before(async () => {
  nock('https://dev.azure.com')
    .get(centosAzureUri)
    .times(5)
    .reply(201, [
    ...

如果我使用字符串,它工作得很好。一个例子如下: const centosAzureUri = `/${conf.org}/${conf.buildProject}/_apis/build/builds?api-version=4.1&branchName=${conf.buildBranch}`

但是,我想使用 RegEx,如下所示: const centosAzureUri = new RegExp(`/${conf.org}/${conf.buildProject}/_apis/build/builds?api-version=4.1.*`, 'g') 那是行不通的。

根据文档,nock 应该接受正则表达式,.* 应该匹配任何符号 [因为 .] 并允许这些匹配的字符重复任意次数。因此,我假设这应该接受任何字符串结尾,包括&branchName=${conf.buildBranch}

我做错了什么?

【问题讨论】:

    标签: javascript node.js regex nock


    【解决方案1】:

    我认为 nock 只使用正则表达式文字与将返回一个新对象的正则表达式对象。例如。

      nock('http://example.com')
           .get(/harry\/[^\/]+$/)
           .query({param1: 'value'})
           .reply(200, "OK");
    

    查看相关 How to build nock regex for dynamic urls

    【讨论】:

    • 谢谢。文字正在工作。就个人而言,我没有看到任何书面或nock 代码中的内容会阻止RegEx 对象工作。同时,听从了您的建议。
    【解决方案2】:

    请注意,RegExp 只需要“4.1”以下的模式来执行匹配。如果匹配发生,字符串的其余部分将被忽略。例如:

    const centosAzureUri = new RegExp(`/${conf.org}/${conf.buildProject}/_apis/build/builds?api-version=4.1`, 'g')
    

    此外,您可能想尝试擒纵机构,因为斜线需要这些:

    const centosAzureUri = new RegExp(`\/${conf.org}\/${conf.buildProject}\/_apis\/build\/builds?api-version=4.1`, 'g')
    

    HTH!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多