Search code examples
javascriptreactjsjestjsreact-testing-library

Can you print/write the result of screen.debug() to a file?


In one of my tests I am expecting some kind of DOM change. However, the page it's on is quite long.

So what I usually do for smaller components is to use screen.debug() method. But since the file is quite long, I started to also run the test task with DEBUG_PRINT_LIMIT=50000. Now that eventually got the result I got.

But that made me wonder, is it perhaps possible to save the output in a file?


Solution

  • According to the docs, screen.debug is essentially a shortcut for console.log(prettyDOM()).

    So you could just use prettyDOM() directly, and do whatever with the result.

    I would do copy(prettyDOM()) to put it on the clipboard and then paste it in a text file manually (in Chrome) or save it into a file (in node).

    Here is a helper function demonstrating how to use it to create a file with the content of the DOM:

    import fs from "node:fs";
    import { prettyDOM } from "@testing-library/dom";
    
    export function dump(element) {
      fs.mkdirSync("dump", { recursive: true });
      fs.writeFileSync(
        `dump/${Date.now()}.html`,
        prettyDOM(element, 1000000, { highlight: false }) || "");
    };