From 613fc5da06bdfeb245f2233dac2f784c9123ef97 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Mon, 24 Aug 2020 18:28:26 -0500 Subject: [PATCH] Add Pretty Print Some Dom To Debug A Test as a RTL til --- README.md | 3 +- .../pretty-print-some-dom-to-debug-a-test.md | 32 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 react-testing-library/pretty-print-some-dom-to-debug-a-test.md diff --git a/README.md b/README.md index 183741f..16b3b83 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_948 TILs and counting..._ +_949 TILs and counting..._ --- @@ -692,6 +692,7 @@ _948 TILs and counting..._ ### React Testing Library - [findBy\* Queries Have Async Built In](react-testing-library/find-by-queries-have-async-built-in.md) +- [Pretty Print Some DOM To Debug A Test](react-testing-library/pretty-print-some-dom-to-debug-a-test.md) - [Test A Component That Uses React Portals](react-testing-library/test-a-component-that-uses-react-portals.md) ### ReasonML diff --git a/react-testing-library/pretty-print-some-dom-to-debug-a-test.md b/react-testing-library/pretty-print-some-dom-to-debug-a-test.md new file mode 100644 index 0000000..637e290 --- /dev/null +++ b/react-testing-library/pretty-print-some-dom-to-debug-a-test.md @@ -0,0 +1,32 @@ +# Pretty Print Some DOM To Debug A Test + +Our test's assertions can help guide what needs to change in the code. +Sometimes those test failures can be too opaque to be helpful. + +It'd be easier if we could just take a peek at how the component is rendering. + +```javascript +import { render, screen } from "@testing-library/react"; +import { prettyDOM } from "@testing-library/dom"; +import "@testing-library/jest-dom/extend-expect"; + +import MyComponent from "../MyComponent"; + +test("renders MyComponent", () => { + const { container } = render(); + + console.log(prettyDOM(container)); + + const nameInput = screen.getByLabelText("Name"); + + console.log(prettyDOM(nameInput)); + + // some expectations +}); +``` + +Passing the rendered container or elements that we've queried for to the +[`prettyDOM`](https://testing-library.com/docs/dom-testing-library/api-helpers#prettydom) +utility creates a formatted, syntax-highlighted version of that part of the +virtual DOM (without all the React Internal noise). This can then be logged out +for debugging purposes.