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的经验.工作解决方案并不像到达那里那样痛苦.非常感谢您的意见和贡献. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
推荐文章
站长推荐
- windows – Delphi:ListView(vsReport)单列标题
- windows – 如何成功更改执行策略并启用PowerShe
- 迁移桌面程序到MS Store(10)——在Windows S M
- 如何在Windows中使用python opencv2在图像上写文
- Windows10操作系统如何在局域网设置打印机共享
- 解决微信小程序要求的TLS版本必须大于等于1.2的问
- 如何在Windows中的接口状态更改上运行脚本?
- windows-server-2008 – 最快的复制文件的方法
- csv – 07002 [Microsoft] [ODBC SQL Server驱动
- Windows 8应用程序中Numericbox的替代品?
热点阅读