How can I output the entire DOM to a file in a JavaScript test?
Testing Library is amazing. But, one area I struggle with it: when writing high-level integration tests, when an assertion fails, the output can be noisy and incomplete. It makes debugging tough.
The test runner says something like:
“I couldn’t find ‘Submit’ in these two thousand lines of HTML, which are so big I’ve truncated for you.”
Where is ‘Submit’? Nobody knows.
Here’s the hack I found: print the entire DOM to a file with
Node’s File System module (fs).
import fs from 'fs';
// Writing the DOM to a file while failing
fs.writeFileSync('dom.html', document.body.innerHTML, 'utf8');
// The failing assertion
screen.getByText(/submit/i)
Now you can inspect dom.html in your text editor and search for ‘Submit.’