2015-11-25 34 views
5

我使用JSDom設置了一些測試,其中我需要windowdocument全局變量,並且還需要爲每個測試傳遞不同的URL/href。如何設置location.hashlocation.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賦值,結果相同。

回答

1

您可以通過在url中輸入#之後輸入字符串來設置location.hash。請參閱以下我的代碼。

var jsdom = require("jsdom"); 

jsdom.env({ 
    url: 'http://localhost?something=not#hash', 'html': '', 
    onload: function(window) { 
     console.log(window.location.href); // http://localhost/?something=not#hash 
     console.log(window.location.hash); // #hash 
    } 
}); 
+0

我意識到我沒有正確地說出我的問題,因爲它主要是爲什麼是空白的。你的回答表明我需要回調。有沒有辦法解決這個問題?這在我的測試中很麻煩,因爲我需要爲每個測試更改href。 – cyberwombat

+0

@Yashua,對!由於頁面加載是異步的,因爲[jsdom guide in github](https://github.com/tmpvar/jsdom),建議使用'config.done,config.onload,config.created.' –

+0

我結束了嘲笑我自己的窗口對象 - jsdom對我的測試來說過分了。 http://stackoverflow.com/questions/4792281/mocking-window-location-href-in-javascript – cyberwombat

5

我也遇到過這個問題,但無法使jsdom.env(...)解決方案正常工作。我結束了以下建議here,並使用jsdom的changeURL函數。我的測試夾具設置看起來像這樣:

beforeEach(function() { 
    // snip... 
    jsdom.changeURL(window, 'http://foo/bar') 
    // snip... 
}) 
0

這一個爲我工作。

Object.defineProperty(window.location, 'href', { 
    writable: true, 
    value: 'some url' 
});