diff --git a/README.md b/README.md index 65c39e2..93333d5 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). -_945 TILs and counting..._ +_946 TILs and counting..._ --- @@ -673,6 +673,7 @@ _945 TILs and counting..._ - [Spelunking Through Components With Enzyme's Dive](react/spelunking-through-components-with-enzymes-dive.md) - [Sync Your react-router State With Redux](react/sync-your-react-router-state-with-redux.md) - [Test Files In create-react-app](react/test-files-in-create-react-app.md) +- [Test That Element Does Not Render In The Component](react/test-that-element-does-not-render-in-the-component.md) - [Trigger Effect Only When The Component Mounts](react/trigger-effect-only-when-the-component-mounts.md) - [Update Formik Initial Values When Props Change](react/update-formik-initial-values-when-props-change.md) - [Upgrading To The Latest React In CodeSandbox](react/upgrading-to-the-latest-react-in-codesandbox.md) diff --git a/react/test-that-element-does-not-render-in-the-component.md b/react/test-that-element-does-not-render-in-the-component.md new file mode 100644 index 0000000..f9adf57 --- /dev/null +++ b/react/test-that-element-does-not-render-in-the-component.md @@ -0,0 +1,36 @@ +# Test That Element Does Not Render In The Component + +With +[`react-testing-library`](https://testing-library.com/docs/react-testing-library/intro), +you can render a component and make assertions about the different parts of the +component that get rendered. + +You can also make assertions that certain things _don't_ get rendered. To do that, first render the component: + +```javascript +import { render, screen } from '@testing-library/react' +import '@testing-library/jest-dom/extend-expect' + +import MyComponent from '../MyComponent' + +test('renders component without Click Me button', () => { + render() +}) +``` + +Then add a `not` expectation with a `query*`-style matcher: + +```javascript + expect(screen.queryByText('Click Me')).not.toBeInTheDocument() +``` + +You'll get an immediate test failure if you try to directly select for the element using a `get*`-style matcher: + + +```javascript + // ❌ will fail on `getByText` before the rest of the + // assertion can be evaluated. + expect(screen.getByText('Click Me')).not.toBeInTheDocument() +``` + +[source](https://kentcdodds.com/blog/common-mistakes-with-react-testing-library#using-query-variants-for-anything-except-checking-for-non-existence)