首页 > 解决方案 > 为什么在调用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"
  }
}

标签: javascriptjestjsconsole.log

解决方案


这不是开玩笑。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()


推荐阅读