Why my html variables are always empty when jest is running? When I directly print them by accessing the innerHTML
variable, the contents are there, but why they do not show up when calling JSON.stringify(obj)
? How can I correctly print them for debugging?
reviewer.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.
package.json
{
"name": "test",
"scripts": {
"test": "jest"
},
"jest": {
"testEnvironment": "jsdom"
},
"devDependencies": {
"jest": "^25.3.0"
}
}
It's not Jest. DOM elements cannot be converted to string using JSON.stringify()
, you could use domJSON for example if you want the full object of the element. If you just want to log the contents, then console.log("things", JSON.stringify(things.outerHTML))
should work.
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>
Potentially you could also use console.dir()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.