我使用JSDom設置了一些測試,其中我需要window
和document
全局變量,並且還需要爲每個測試傳遞不同的URL/href。如何設置location.hash
和location.href
屬性?使用JSDom設置location.hash和location.href
global.document = jsdom({url: 'http://localhost?something=not#test', 'html': ''});
global.window = document.defaultView;
console.log(window.location.href); // returns 'about:blank'
console.log(window.location.hash); // returns no value
我試過直接給window.location.hash
賦值,結果相同。
我意識到我沒有正確地說出我的問題,因爲它主要是爲什麼是空白的。你的回答表明我需要回調。有沒有辦法解決這個問題?這在我的測試中很麻煩,因爲我需要爲每個測試更改href。 – cyberwombat
@Yashua,對!由於頁面加載是異步的,因爲[jsdom guide in github](https://github.com/tmpvar/jsdom),建議使用'config.done,config.onload,config.created.' –
我結束了嘲笑我自己的窗口對象 - jsdom對我的測試來說過分了。 http://stackoverflow.com/questions/4792281/mocking-window-location-href-in-javascript – cyberwombat