在jsDom中设置窗口宽度?

Ski*_*man 7 node.js jsdom

应该是一个简单的问题.如何在jsDom对象中设置宽度?

    jsdom.env({
        url:'http://testdatalocation',
        scripts: ['http://code.jquery.com/jquery.js'],
        done: function(errors, tstWindow) {
            console.log(tstWindow.innerWidth);
};
}
});
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚如何让"innerWidth"成为1024以外的任何东西

Lou*_*uis 5

resizeTo方法resizeBy未实现。通过搜索jsdom的代码库可以看到:

$ grep -P 'resize(To|By)' `find . -type f`
./lib/jsdom/browser/index.js:    resizeBy: NOT_IMPLEMENTED(null, 'window.resizeBy'),
./lib/jsdom/browser/index.js:    resizeTo: NOT_IMPLEMENTED(null, 'window.resizeTo'),
Run Code Online (Sandbox Code Playgroud)

如果您只想在初始化时一次性设置窗口大小,则可以将该innerWidth值设置为您想要的任何值。在真正的浏览器中,这不是正确的方法,但在 jsdom 中它可以工作。

但是,如果您有依赖于resizeTo当前存在的代码,则可以将自己的 polyfill 添加到构建窗口的构造函数中:

var jsdom = require("jsdom");

var document = jsdom.env({
    html: "<html></html>",
    done: function (error, w) {
        console.log(w.innerWidth, w.innerHeight);
        w.constructor.prototype.resizeTo = function (width, height) {
            this.innerWidth = this.outerWidth = width;
            this.innerHeight = this.outerHeight = height;
        };
        w.resizeTo(100, 200);
        console.log(w.innerWidth, w.innerHeight);
    }
});
Run Code Online (Sandbox Code Playgroud)

这显示:

1024 768
100 200
Run Code Online (Sandbox Code Playgroud)

上面的代码用于说明目的。我还没有考虑过为resizeTo. resizeBy将进行类似的处理,但会向窗口的大小添加增量。


Jon*_*ski 3

目前还没有正式的选项或 API 可以实现此目的。

innerWidth和类似属性的值简单地设置为文字值

DOMWindow.prototype = createFrom(dom || null, {
  // ...
  name: 'nodejs',
  innerWidth: 1024,
  innerHeight: 768,
  outerWidth: 1024,
  outerHeight: 768,
  // ...
});
Run Code Online (Sandbox Code Playgroud)

除了测试用例和文档之外,outerWidthjsdom 中的其他地方没有引用,因此您可以在createdeventouterWidth中分配一个新值,并进行更新。

主要用例created是在执行任何脚本之前修改窗口对象(例如,在内置原型上添加新函数)。

created: function (errors, tstWindow) {
    tstWindow.outerWidth = tstWindow.innerWidth = 1440;
},
done: function(errors, tstWindow) {
    console.log(tstWindow.innerWidth);
}
Run Code Online (Sandbox Code Playgroud)