我想测试一个调用window.location.search的简单函数。我试图了解如何存根这个电话,以便我可以返回我选择的网址。sinon stub for 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")
这当然,不工作。我不认为我正确地指定了存根,但它显示了我的意图。
任何想法如何解决这将不胜感激。
我试过之前,我只是试过一遍:'TypeError:试图包装字符串属性搜索作为函数' – 2012-08-14 21:16:16
哦对不起,'window.location.search'是一个字符串不是一个函数,所以你可以不存在。将该存根替换为一个赋值:'window.location.search =“myUrl”'。 – 2012-08-14 21:24:38
奇怪的是,在执行一个console.log之前和之后导致一个空字符串,所以我不知道发生了什么。这项任务并不坚持。我更新了我的代码以显示我的测试用例。 – 2012-08-14 22:05:33