我想測試一個調用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