使用JSDom设置location.hash和location.href

cyb*_*bat 6 javascript jsdom

我正在使用JSDom设置一些测试,我需要windowdocument全局变量,并且还需要为每个测试传递不同的URL/href.如何设置location.hashlocation.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
Run Code Online (Sandbox Code Playgroud)

我试过直接赋值给出window.location.hash相同的结果.

Alf*_*red 1

您可以location.hash通过在 url 后面输入字符串来设置#。参考我的代码。

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
    }
});
Run Code Online (Sandbox Code Playgroud)