mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 07:08:01 +00:00
Add Check That A Component Renders As Null as a react-testing-library til
This commit is contained in:
@@ -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).
|
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
|
### 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)
|
- [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)
|
- [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)
|
- [Test A Component That Uses React Portals](react-testing-library/test-a-component-that-uses-react-portals.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 <span>{message}</span>;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
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 `<div>`. Knowing
|
||||||
|
this, we can check if a component renders to `null` by checking the contents of
|
||||||
|
the wrapping `<div>` 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(
|
||||||
|
<HiddenMessage hidden message="You can't see me!" />
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(container.firstChild).toBeNull();
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
The component renders as `null`, so the `firstChild` of the RTL `container`
|
||||||
|
will be `null`.
|
||||||
Reference in New Issue
Block a user