javascript - 为什么在调用console.log的时候jest document.createElement('div')等元素都是空的?
问题描述
为什么 jest 运行时我的 html 变量总是空的?当我通过访问变量直接打印它们时innerHTML
,内容就在那里,但是为什么它们在调用时不显示JSON.stringify(obj)
?如何正确打印它们以进行调试?
审阅者.test.js
test('renders test site', () => {
const things = document.createElement('div');
things.id = "things";
things.innerHTML = '<div>some.</div>';
console.log('things', things)
console.log('things', JSON.stringify(things))
document.body.appendChild(things);
console.log('document.body', document.body)
console.log('document.body', JSON.stringify(document.body))
document.body.innerHTML = '<div id="test"><div class="panel-block"></div>....</div>';
console.log('document.body', document.body)
console.log('document.body', JSON.stringify(document.body))
});
$ npx jest
PASS src/reviewer.test.js
√ renders test site (31ms)
console.log src/reviewer.test.js:19
things HTMLDivElement {}
console.log src/reviewer.test.js:20
things {}
console.log src/reviewer.test.js:23
document.body HTMLBodyElement {}
console.log src/reviewer.test.js:24
document.body {}
console.log src/reviewer.test.js:27
document.body HTMLBodyElement {}
console.log src/reviewer.test.js:28
document.body {}
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 2.358s
Ran all test suites.
包.json
{
"name": "test",
"scripts": {
"test": "jest"
},
"jest": {
"testEnvironment": "jsdom"
},
"devDependencies": {
"jest": "^25.3.0"
}
}
解决方案
这不是开玩笑。DOM 元素不能使用 转换为字符串,例如,如果您想要元素的完整对象,JSON.stringify()
可以使用domJSON 。如果您只想记录内容,那么console.log("things", JSON.stringify(things.outerHTML))
应该可以。
const things = document.createElement("div");
things.id = "things";
things.innerHTML = "<div>some.</div>";
console.log("things", things);
console.log("things", JSON.stringify(things.outerHTML))
console.log("things", domJSON.toJSON(things));
<script src="https://cdn.jsdelivr.net/npm/domjson@0.1.2/dist/domJSON.min.js"></script>
潜在地你也可以使用console.dir()
推荐阅读
- python - 解决具有指定间隔的三角函数 sympy Python
- java - 持久化新对象的正确方法是什么?使用@RequestBody 接收构建的json 对象或接收许多@RequestParam?
- android - Android 设备无法通过 adb shell ping PC
- amazon-web-services - Cloud Watch 代理立即停止
- aws-lambda - AWS CDK:如何将 build_args 传递给 DockerImageCode.from_image_asset
- python - 使用 cut 函数对数值列进行 bin 会创建 NAN 值
- python - 有人可以解释这行代码吗?
- r - 当`c()`为`0`时,如何使用`[c(),]`对数据帧进行子集化?
- postgresql - Case..When in Where Condition Spring 引导数据 jpa
- json - 请问如何将 cURL 转换为 JSON?