From 1e0ce58e15526e0284443f7e003a53a40b825cfc Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Wed, 30 Sep 2020 16:15:08 -0500 Subject: [PATCH] Add Check That A Component Renders As Null as a react-testing-library til --- README.md | 3 +- .../check-that-a-component-renders-as-null.md | 37 +++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 react-testing-library/check-that-a-component-renders-as-null.md diff --git a/README.md b/README.md index 877d70a..7457b4e 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). -_952 TILs and counting..._ +_953 TILs and counting..._ --- @@ -694,6 +694,7 @@ _952 TILs and counting..._ ### React Testing Library +- [Check That A Component Renders As Null](react-testing-library/check-that-a-component-renders-as-null.md) - [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) diff --git a/react-testing-library/check-that-a-component-renders-as-null.md b/react-testing-library/check-that-a-component-renders-as-null.md new file mode 100644 index 0000000..bc8e179 --- /dev/null +++ b/react-testing-library/check-that-a-component-renders-as-null.md @@ -0,0 +1,37 @@ +# Check That A Component Renders As Null + +Consider a component that sometimes renders as `null`. + +```javascript +const HiddenMessage = ({ message, hidden }) => { + if (hidden) return null; + + return {message}; +}; +``` + +How can we test the version of this component that renders as `null` when +`hidden` is `true`? + +When +[react-testing-library](https://testing-library.com/docs/react-testing-library/intro) +renders a component, it wraps the whole thing in a surrounding `
`. Knowing +this, we can check if a component renders to `null` by checking the contents of +the wrapping `
` container. + +```javascript +import React from "react"; +import { render } from "@testing-library/react"; +import "@testing-library/jest-dom/extend-expect"; + +test("renders as null", () => { + const { container } = render( +