使用JSDom设置location.hash和location.href
问题描述:
我使用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
赋值,结果相同。
答
您可以通过在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
}
});
答
我也遇到过这个问题,但无法使jsdom.env(...)
解决方案正常工作。我结束了以下建议here,并使用jsdom的changeURL
函数。我的测试夹具设置看起来像这样:
beforeEach(function() {
// snip...
jsdom.changeURL(window, 'http://foo/bar')
// snip...
})
答
这一个为我工作。
Object.defineProperty(window.location, 'href', {
writable: true,
value: 'some url'
});
我意识到我没有正确地说出我的问题,因为它主要是为什么是空白的。你的回答表明我需要回调。有没有办法解决这个问题?这在我的测试中很麻烦,因为我需要为每个测试更改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