我目前正在开发一个项目,要求我通过JSDOM将计算样式发送到浏览器.我目前正在寻找一种方法将一些基本的CSS注入JSDOM,以便它可以计算出正确的内联样式(是的,我知道这很糟糕).
根据我的发现,我可以使用JSDOM Level 2,但是从那里我找不到任何关于如何注入样式的文档这是我到目前为止所拥有的
var document = jsdom.jsdom('<!DOCTYPE html><html><head></head><body id="abody" ></body></html>', jsdom.level(2, 'style'), {
features : {
FetchExternalResources : ['script', 'css'],
QuerySelector : true
}
});
Run Code Online (Sandbox Code Playgroud)
我一直在将css插入head标签,但无济于事.而且我知道我也可以做错上面的代码.
任何帮助都会很棒.
我尝试安装jsdom这样:
$ sudo npm install -g jsdom
# OR
$ sudo npm install jsdom
Run Code Online (Sandbox Code Playgroud)
在一些成功的命令之后,安装很快就会失败,第一条错误消息在[....]:
$ sudo npm install jsdom
npm http GET https://registry.npmjs.org/jsdom
npm http 304 https://registry.npmjs.org/jsdom
[....]
> contextify@0.1.7 install /home/yug/Desktop/QGis/WikiAtlas/1_shaded_relief/test/node_modules/jsdom/node_modules/contextify
> node-gyp rebuild
gyp: /home/yug/.node-gyp/0.10.25/common.gypi not found (cwd: /home/yug/Desktop/QGis/WikiAtlas/1_shaded_relief/test/node_modules/jsdom/node_modules/contextify) while reading includes of binding.gyp
gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack at ChildProcess.onCpExit (/usr/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:337:16)
gyp ERR! stack at ChildProcess.EventEmitter.emit (events.js:98:17)
gyp ERR! stack at Process.ChildProcess._handle.onexit …Run Code Online (Sandbox Code Playgroud) 摘要:
我试图测试一个侦听其中的本机DOM事件的React组件componentWillMount.
我发现jsdom(@8.4.0)在调度事件和添加事件监听器时没有按预期工作.
我可以提取的最简单的代码:
window.addEventListener('click', () => {
throw new Error("success")
})
const event = new Event('click')
document.dispatchEvent(event)
throw new Error('failure')
Run Code Online (Sandbox Code Playgroud)
这引发了"失败".
语境:
这是我试图测试的组件的提取/简化版本.你可以在Webpackbin上看到它.
import React from 'react'
export default class Example extends React.Component {
constructor() {
super()
this._onDocumentClick = this._onDocumentClick.bind(this)
}
componentWillMount() {
this.setState({ clicked: false })
window.addEventListener('click', this._onDocumentClick)
}
_onDocumentClick() {
const clicked = this.state.clicked || false
this.setState({ clicked: !clicked })
}
render() {
return <p>{JSON.stringify(this.state.clicked)}</p>
}
} …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用sinon的mock和spy来测试Redux组件和异步操作,但是只要我将sinon导入任何测试文件,运行以下npm脚本:
mocha --require test/helpers/browser.js --compilers.:babel-core/register --opts test/client/**/*.{js,jsx} --recursive test/client
我收到以下错误:
var div = typeof document !== "undefined" && document.createElement("div");
^
Run Code Online (Sandbox Code Playgroud)
TypeError:document.createElement不是.../node_modules/sinon/lib/sinon/util/core/deep-equal.js中的函数:3:55
browser.js是我设置JSDOM的地方:
import { JSDOM } from 'jsdom';
const doc = new JSDOM('<!DOCTYPE html><html><head></head><body></body></html>');
cost win = doc.defaultView; // tried doc.window;
global.document = doc;
global.window = win;
/*
Object.keys(win).forEach(property => {
if (typeof global[property] === 'undefined') {
global[property] = win[property];
}
});
*/
global.navigator = {
userAgent: 'node.js'
};
Run Code Online (Sandbox Code Playgroud)
我想我没有正确设置jsdom?我试着环顾四周,在上面的browser.js文件中找到了注释代码,但是在取消注释时会产生错误:
Object.keys(win).forEach(function (property) {
^
Run Code Online (Sandbox Code Playgroud)
TypeError:无法将undefined或null转换为object.
我们正在编写离线第一个应用程序基础知识的教程,并使用带磁带的JSDOM来测试我们的代码.在我们的代码中,我们更新DOM,以便通过将事件监听器附加到窗口并监听"在线"/"离线"事件,将文本节点从"在线"更改为"离线",反之亦然,并navigator.onLine初始化文本到在线/离线.像这样:
// get the online status element from the DOM
var onlineStatusDom = document.querySelector('.online-status');
// navigator.onLine will be true when online and false when offline. We update the text in the online status element in the dom to reflect the online status from navigator.onLine
if (navigator.onLine) {
onlineStatusDom.innerText = 'online';
} else {
onlineStatusDom.innerText = 'offline';
}
// we use the 'online' and 'offline' events to update the online/offline notification to the user
// in IE8 the offline/online …Run Code Online (Sandbox Code Playgroud) 我的网络应用程序使用自定义 ReadableStream 读取本地文件(这样我就不需要平台支持的最大文件大小),并且它对于格式正确的文件和错误文件都非常有效。我的应用程序是使用 React-Redux-Saga 构建的。
我现在尝试e2e向我的代码添加有限的测试来测试状态管理。我正在测试发送redux操作时状态是否正确更新。我正在使用 package 测试传奇redux-saga-tester。
在运行使用我构建的 ReadableStream 读取本地文件的 jest 客户端测试时,出现错误ReferenceError: ReadableStream is not defined。我的理解是使用的jsdom环境jest缺少 ReadableStream 实现。然后我添加了web-streams-polyfill包来填充 ReadableStream 类。
现在验证文件测试正在通过,就像在浏览器中一样:
test('Select and validate log file', async () => {
const testFile = testFileBuilder.valid();
storeTester.dispatch(fileSelected(testFile));
await storeTester.waitFor(FILE_VALIDATED);
const state = storeTester.getState().file;
expect(state.fileValidated).toBeTruthy();
});
Run Code Online (Sandbox Code Playgroud)
我的问题是,当我使用无效文件运行第二次验证测试时,测试通过,但在控制台上打印错误。
考试:
test('Select an invalid file - JSON error', async () => {
const testFile = testFileBuilder.errorJSON();
storeTester.dispatch(fileSelected(testFile));
await storeTester.waitFor(FILE_ERROR);
const state …Run Code Online (Sandbox Code Playgroud) 我想知道我是否可以获得DOM元素的实际宽度和坐标,因为我可以在浏览器中使用.clientWidth/.offsetWidth.
jsdom是否具有浏览器渲染功能以获取此数据?
如果没有,我怎么能在node.js服务器中得到它?
谢谢!
我正在尝试为类似文字处理器的操作编写单元测试,例如将列表应用于文本节点,但我发现这document.execCommand不适用于jsdom,所以我对如何对以下操作进行单元测试感到困惑:
document.getElementById('run').addEventListener('click', function() {
document.execCommand("insertorderedlist");
});Run Code Online (Sandbox Code Playgroud)
<div contenteditable="true">Foo</div>
<button id="run">Select "Foo" then Click</button>Run Code Online (Sandbox Code Playgroud)
注意:这个问题不是其他现有问题的重复,因为这个问题不使用jsdom.env()旧版本的 JSDOM 使用的函数调用。
文件bar.js:
console.log('bar says: hello')
Run Code Online (Sandbox Code Playgroud)
文件foo.js:
var jsdom = require('jsdom')
var html = '<!DOCTYPE html><head><script src="bar.js"></script></head><body><div>Foo</div></body>'
var window = new jsdom.JSDOM(html).window
window.onload = function () {
console.log('window loaded')
}
Run Code Online (Sandbox Code Playgroud)
当我运行时foo.js,我得到这个输出。
$ node foo.js
window loaded
Run Code Online (Sandbox Code Playgroud)
为什么bar says: hello输出没有来?好像bar.js没有加载。如何jsdom在script标签中加载文件?
[编辑/解决方案]:在遵循 Quentin 的答案中的建议后问题已解决。此代码有效:
var jsdom = require('jsdom')
var html = '<!DOCTYPE html><head><script src="bar.js"></script></head><body><div>Foo</div></body>'
var window = new jsdom.JSDOM(html, { runScripts: "dangerously", resources: …Run Code Online (Sandbox Code Playgroud) 类似的问题在这里 -无法检查 expect(elm).not.toBeVisible() 的语义 UI 反应组件- 但是答案表明这应该适用于 CSS-in-JS,这就是我正在使用的。
我正在使用 Material-UI 的<Hidden>组件仅在sm屏幕尺寸及更大尺寸上显示一些文本。这是代码(在生产中完美运行):
<Hidden implementation="css" xsDown>
<LogoText variant="h5" component="p" />
</Hidden>
Run Code Online (Sandbox Code Playgroud)
我使用的是jest-dom与react-testing-library和我想测试我的导航栏,其中包含这个隐藏文本的响应。
我有以下测试:
const initTest = width => {
Object.defineProperty(window, "innerWidth", {
writable: true,
configurable: true,
value: width
});
window.matchMedia = jest.fn().mockImplementation(
query => {
return {
matches: width >= theme.breakpoints.values.sm ? true : false,
media: query,
onchange: null,
addListener: jest.fn(),
removeListener: jest.fn()
};
}
);
const height = Math.round((width * 9) …Run Code Online (Sandbox Code Playgroud) jsdom ×10
node.js ×6
javascript ×4
testing ×3
jestjs ×2
mocha.js ×2
redux ×2
contextify ×1
css ×1
material-ui ×1
node-gyp ×1
npm ×1
redux-saga ×1
sinon ×1