Mic*_*son 5 stubbing coffeescript sinon buster.js
我试图测试一个调用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, " "))
Run Code Online (Sandbox Code Playgroud)
测试用例:
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)
Run Code Online (Sandbox Code Playgroud)
我最初的尝试是直接返回一个值:
sinon.stub(window.location.search).returns("myUrl")
Run Code Online (Sandbox Code Playgroud)
当然,这不起作用.我认为我没有正确指定存根,但它显示了我的意图.
如何解决这个问题的任何想法将不胜感激.
所以,如前所述,你不能直接模拟window.location.mylib.search包装器的想法也不适用于我的情况.所以,我所做的就是打破我window.location.search自己的功能.我的新班看起来像这样:
getParameterByName: (name) =>
console.log("name: #{name}")
name = name.replace(/[\[]/, "\\\[").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
Run Code Online (Sandbox Code Playgroud)
然后在我的测试用例中,我用我的测试代码替换函数,如下所示:
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")
Run Code Online (Sandbox Code Playgroud)
对于那些没有阅读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);
});
Run Code Online (Sandbox Code Playgroud)
这是我通常使用Javascript的经验.工作解决方案并不像到达那里那样痛苦.非常感谢您的意见和贡献.
| 归档时间: |
|
| 查看次数: |
8841 次 |
| 最近记录: |