加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

coffeescript – 用于window.location.search的sinon存根

发布时间:2020-12-14 02:03:12 所属栏目:Windows 来源:网络整理
导读:我试图测试一个调用window.location.search的简单函数.我正在尝试了解如何存根此调用,以便我可以返回我选择的网址. 功能: getParameterByName: (name) = name = name.replace(/[[]/,"[").replace(/[]]/,"]") regexS = "[?]" + name + "=([^#]*)"
我试图测试一个调用window.location.search的简单函数.我正在尝试了解如何存根此调用,以便我可以返回我选择的网址.

功能:

getParameterByName: (name) =>    
  name = name.replace(/[[]/,"[").replace(/[]]/,"]")
  regexS = "[?&]" + name + "=([^&#]*)"
  regex = new RegExp(regexS)    
  results = regex.exec(window.location.search) //Stub call to window.location.search
  if(results == null)
    return ""
  else
    return decodeURIComponent(results[1].replace(/+/g," "))

测试用例:

describe "Data tests",() ->
  it "Should parse parameter from url",() ->        
    data = new Data()

    console.log("search string: " + window.location.search) //prints "search string:"
    window.location.search = "myUrl"
    console.log("search string: " + window.location.search) //prints "search string:"
    console.log(data.getParameterByName('varName'))

    expect(true).toBe(true)

我最初的尝试是直接返回一个值:

sinon.stub(window.location.search).returns("myUrl")

当然,这不起作用.我认为我没有正确指定存根,但它显示了我的意图.

如何解决这个问题的任何想法将不胜感激.

解决方法

所以,如前所述,你不能直接模拟window.location. mylib.search包装器的想法也不适用于我的情况.所以,我所做的是将我对window.location.search的调用分解为它自己的函数.我的新班看起来像这样:

getParameterByName: (name) =>
  console.log("name: #{name}")
  name = name.replace(/[[]/,"]")
  regexS = "[?&]" + name + "=([^&#]*)"
  regex = new RegExp(regexS)
  results = regex.exec(@getWindowLocationSearch())
  if(results == null)
    return ""
  else
    return decodeURIComponent(results[1].replace(/+/g," "))

getWindowLocationSearch:() =>
  window.location.search

然后在我的测试用例中,我用我的测试代码替换函数,如下所示:

describe "Data tests",() ->
  it "Should parse parameter from localhost url",() ->
    goodUrl = "http://localhost:3333/?token=val1"

    Data::getWindowLocationSearch = () -> return goodUrl
    unit = new Data()
    result = unit.getParameterByName("token")

    expect(result).toBe("val1")

对于那些没有阅读Coffeescript的人,下面列出了等效的javascript代码:

it("Should parse parameter from localhost url",function() {
  var goodUrl,result,unit;
  goodUrl = "http://localhost:3333/?token=val1";
  Data.prototype.getWindowLocationSearch = function() {
    return goodUrl;
  };
  unit = new Data();
  result = unit.getParameterByName("token");
  expect(result).toBe("val1");
  return expect(true).toBe(true);
});

这是我通常使用Javascript的经验.工作解决方案并不像到达那里那样痛苦.非常感谢您的意见和贡献.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读