【问题标题】:Sinon fakeserver url regexpSinon fakeserver url 正则表达式
【发布时间】:2015-05-11 14:44:15
【问题描述】:

根据documentation,Sinon fakeserver 可以使用正则表达式模式来匹配 URL:

server.respondWith(method, urlRegExp, response);

我想匹配所有以foo=1 结尾的网址。这是我的尝试:

this.server.respondWith('GET', '/foo=1$/', [200, 
{ 'Content-Type': 'application/json' }, '{ "foo": 1 }']);

但是,它似乎不起作用。我的正则表达式可能是错误的,但我需要你的帮助来调整它。

http://jsfiddle.net/s38qw3ns/1/

【问题讨论】:

  • 查看该站点上的示例:server.respondWith(/\/todo-items\/(\d+)/, function (xhr, id) { xhr.respond(200, { ?Content-Type?: ?application/json? }, ?[{ ?id?: ? + id + ? }]?); });。有一个使用idfunctionid 是正则表达式中的第一个捕获组。也许,您还需要使用/foo=(\d+)/ 正则表达式捕获组,并将id 与函数一起使用。

标签: javascript regex unit-testing sinon


【解决方案1】:

你的正则表达式有单引号,所以 sinon 将它视为一个字符串(它是:)。

去掉单引号,它将是一个正则表达式,并按您的预期工作。

this.server.respondWith('GET', /foo=1$/, [200, { 'Content-Type': 'application/json' }, '{ "foo": 1 }']);

请参阅 MDN 上的 Creating a regular expression 以供参考。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    • 2011-11-09
    相关资源
    最近更新 更多