1616[ ![ downloads] [ downloads-badge ]] [ npmtrends ]
1717[ ![ MIT License] [ license-badge ]] [ license ]
1818
19- [ ![ All Contributors] ( https://img.shields.io/badge/all_contributors-5 -orange.svg?style=flat-square )] ( #contributors )
19+ [ ![ All Contributors] ( https://img.shields.io/badge/all_contributors-6 -orange.svg?style=flat-square )] ( #contributors )
2020[ ![ PRs Welcome] [ prs-badge ]] [ prs ]
2121[ ![ Code of Conduct] [ coc-badge ]] [ coc ]
2222
@@ -86,18 +86,18 @@ test('Fetch makes an API call and displays the greeting when load-greeting is cl
8686 }),
8787 )
8888 const url = ' /greeting'
89- const {queryByTestId , container } = render (< Fetch url= {url} / > )
89+ const {getByTestId , container } = render (< Fetch url= {url} / > )
9090
9191 // Act
92- Simulate .click (queryByTestId (' load-greeting' ))
92+ Simulate .click (getByTestId (' load-greeting' ))
9393
9494 // let's wait for our mocked `get` request promise to resolve
9595 await flushPromises ()
9696
9797 // Assert
9898 expect (axiosMock .get ).toHaveBeenCalledTimes (1 )
9999 expect (axiosMock .get ).toHaveBeenCalledWith (url)
100- expect (queryByTestId (' greeting-text' ).textContent ).toBe (' hello there' )
100+ expect (getByTestId (' greeting-text' ).textContent ).toBe (' hello there' )
101101 expect (container .firstChild ).toMatchSnapshot ()
102102})
103103```
@@ -146,18 +146,34 @@ unmount()
146146// your component has been unmounted and now: container.innerHTML === ''
147147```
148148
149+ #### ` getByTestId `
150+
151+ A shortcut to `` container.querySelector(`[data-testid="${yourId}"]`) `` except
152+ that it will throw an Error if no matching element is found. Read more about
153+ ` data-testid ` s below.
154+
155+ ``` javascript
156+ const usernameInputElement = getByTestId (' username-input' )
157+ usernameInputElement .value = ' new value'
158+ Simulate .change (usernameInputElement)
159+ ```
160+
149161#### ` queryByTestId `
150162
151- A shortcut to `` container.querySelector(`[data-testid="${yourId}"]`) `` . Read
152- more about ` data-testid ` s below.
163+ A shortcut to `` container.querySelector(`[data-testid="${yourId}"]`) ``
164+ (Note: just like ` querySelector ` , this could return null if no matching element
165+ is found, which may lead to harder-to-understand error messages). Read more about
166+ ` data-testid ` s below.
153167
154168``` javascript
155- const usernameInputElement = queryByTestId (' username-input' )
169+ // assert something doesn't exist
170+ // (you couldn't do this with `getByTestId`)
171+ expect (queryByTestId (' username-input' )).toBeNull ()
156172```
157173
158174## More on ` data-testid ` s
159175
160- The ` queryByTestId ` utility is referring to the practice of using ` data-testid `
176+ The ` getByTestId ` and ` queryByTestId ` utilities refer to the practice of using ` data-testid `
161177attributes to identify individual elements in your rendered component. This is
162178one of the practices this library is intended to encourage.
163179
@@ -186,14 +202,14 @@ prefer to update the props of a rendered component in your test, the easiest
186202way to do that is:
187203
188204``` javascript
189- const {container , queryByTestId } = render (< NumberDisplay number= {1 } / > )
190- expect (queryByTestId (' number-display' ).textContent ).toBe (' 1' )
205+ const {container , getByTestId } = render (< NumberDisplay number= {1 } / > )
206+ expect (getByTestId (' number-display' ).textContent ).toBe (' 1' )
191207
192208// re-render the same component with different props
193209// but pass the same container in the options argument.
194210// which will cause a re-render of the same instance (normal React behavior).
195211render (< NumberDisplay number= {2 } / > , {container})
196- expect (queryByTestId (' number-display' ).textContent ).toBe (' 2' )
212+ expect (getByTestId (' number-display' ).textContent ).toBe (' 2' )
197213```
198214
199215[ Open the tests] ( https://github.com/kentcdodds/react-testing-library/blob/master/src/__tests__/number-display.js )
@@ -219,14 +235,16 @@ jest.mock('react-transition-group', () => {
219235})
220236
221237test (' you can mock things with jest.mock' , () => {
222- const {queryByTestId } = render (< HiddenMessage initialShow= {true } / > )
238+ const {getByTestId , queryByTestId } = render (
239+ < HiddenMessage initialShow= {true } / > ,
240+ )
223241 expect (queryByTestId (' hidden-message' )).toBeTruthy () // we just care it exists
224242 // hide the message
225- Simulate .click (queryByTestId (' toggle-message' ))
243+ Simulate .click (getByTestId (' toggle-message' ))
226244 // in the real world, the CSSTransition component would take some time
227245 // before finishing the animation which would actually hide the message.
228246 // So we've mocked it out for our tests to make it happen instantly
229- expect (queryByTestId (' hidden-message' )).toBeFalsy () // we just care it doesn't exist
247+ expect (queryByTestId (' hidden-message' )).toBeNull () // we just care it doesn't exist
230248})
231249```
232250
@@ -247,6 +265,14 @@ something more
247265Learn more about how Jest mocks work from my blog post:
248266[ "But really, what is a JavaScript mock?"] ( https://blog.kentcdodds.com/but-really-what-is-a-javascript-mock-10d060966f7d )
249267
268+ ** What if I want to verify that an element does NOT exist?**
269+
270+ You typically will get access to rendered elements using the ` getByTestId ` utility. However, that function will throw an error if the element isn't found. If you want to specifically test for the absence of an element, then you should use the ` queryByTestId ` utility which will return the element if found or ` null ` if not.
271+
272+ ``` javascript
273+ expect (queryByTestId (' thing-that-does-not-exist' )).toBeNull ()
274+ ```
275+
250276** I don't want to use ` data-testid ` attributes for everything. Do I have to?**
251277
252278Definitely not. That said, a common reason people don't like the ` data-testid `
@@ -286,18 +312,18 @@ Or you could include the index or an ID in your attribute:
286312< li data- testid= {` item-${ item .id } ` }> {item .text }< / li>
287313```
288314
289- And then you could use the ` queryByTestId ` :
315+ And then you could use the ` getByTestId ` utility :
290316
291317``` javascript
292318const items = [
293319 /* your items */
294320]
295- const {queryByTestId } = render (/* your component with the items */ )
296- const thirdItem = queryByTestId (` item-${ items[2 ].id } ` )
321+ const {getByTestId } = render (/* your component with the items */ )
322+ const thirdItem = getByTestId (` item-${ items[2 ].id } ` )
297323```
298324
299325** What about enzyme is "bloated with complexity and features" and "encourage poor testing
300- practices"**
326+ practices"? **
301327
302328Most of the damaging features have to do with encouraging testing implementation
303329details. Primarily, these are
@@ -358,8 +384,8 @@ Thanks goes to these people ([emoji key][emojis]):
358384<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
359385
360386<!-- prettier-ignore -->
361- | [<img src="https://avatars.githubusercontent.com/u/1500684?v=3" width="100px;"/><br /><sub><b>Kent C. Dodds</b></sub>](https://kentcdodds.com)<br />[💻](https://github.com/kentcdodds/react-testing-library/commits?author=kentcdodds "Code") [📖](https://github.com/kentcdodds/react-testing-library/commits?author=kentcdodds "Documentation") [🚇](#infra-kentcdodds "Infrastructure (Hosting, Build-Tools, etc)") [⚠️](https://github.com/kentcdodds/react-testing-library/commits?author=kentcdodds "Tests") | [<img src="https://avatars1.githubusercontent.com/u/2430381?v=4" width="100px;"/><br /><sub><b>Ryan Castner</b></sub>](http://audiolion.github.io)<br />[📖](https://github.com/kentcdodds/react-testing-library/commits?author=audiolion "Documentation") | [<img src="https://avatars0.githubusercontent.com/u/8008023?v=4" width="100px;"/><br /><sub><b>Daniel Sandiego</b></sub>](https://www.dnlsandiego.com)<br />[💻](https://github.com/kentcdodds/react-testing-library/commits?author=dnlsandiego "Code") | [<img src="https://avatars2.githubusercontent.com/u/12592677?v=4" width="100px;"/><br /><sub><b>Paweł Mikołajczyk</b></sub>](https://github.com/Miklet)<br />[💻](https://github.com/kentcdodds/react-testing-library/commits?author=Miklet "Code") | [<img src="https://avatars3.githubusercontent.com/u/464978?v=4" width="100px;"/><br /><sub><b>Alejandro Ñáñez Ortiz</b></sub>](http://co.linkedin.com/in/alejandronanez/)<br />[📖](https://github.com/kentcdodds/react-testing-library/commits?author=alejandronanez "Documentation") |
362- | :---: | :---: | :---: | :---: | :---: |
387+ | [<img src="https://avatars.githubusercontent.com/u/1500684?v=3" width="100px;"/><br /><sub><b>Kent C. Dodds</b></sub>](https://kentcdodds.com)<br />[💻](https://github.com/kentcdodds/react-testing-library/commits?author=kentcdodds "Code") [📖](https://github.com/kentcdodds/react-testing-library/commits?author=kentcdodds "Documentation") [🚇](#infra-kentcdodds "Infrastructure (Hosting, Build-Tools, etc)") [⚠️](https://github.com/kentcdodds/react-testing-library/commits?author=kentcdodds "Tests") | [<img src="https://avatars1.githubusercontent.com/u/2430381?v=4" width="100px;"/><br /><sub><b>Ryan Castner</b></sub>](http://audiolion.github.io)<br />[📖](https://github.com/kentcdodds/react-testing-library/commits?author=audiolion "Documentation") | [<img src="https://avatars0.githubusercontent.com/u/8008023?v=4" width="100px;"/><br /><sub><b>Daniel Sandiego</b></sub>](https://www.dnlsandiego.com)<br />[💻](https://github.com/kentcdodds/react-testing-library/commits?author=dnlsandiego "Code") | [<img src="https://avatars2.githubusercontent.com/u/12592677?v=4" width="100px;"/><br /><sub><b>Paweł Mikołajczyk</b></sub>](https://github.com/Miklet)<br />[💻](https://github.com/kentcdodds/react-testing-library/commits?author=Miklet "Code") | [<img src="https://avatars3.githubusercontent.com/u/464978?v=4" width="100px;"/><br /><sub><b>Alejandro Ñáñez Ortiz</b></sub>](http://co.linkedin.com/in/alejandronanez/)<br />[📖](https://github.com/kentcdodds/react-testing-library/commits?author=alejandronanez "Documentation") | [<img src="https://avatars0.githubusercontent.com/u/1402095?v=4" width="100px;"/><br /><sub><b>Matt Parrish</b></sub>](https://github.com/pbomb)<br />[🐛](https://github.com/kentcdodds/react-testing-library/issues?q=author%3Apbomb "Bug reports") [💻](https://github.com/kentcdodds/react-testing-library/commits?author=pbomb "Code") [📖](https://github.com/kentcdodds/react-testing-library/commits?author=pbomb "Documentation") [⚠️](https://github.com/kentcdodds/react-testing-library/commits?author=pbomb "Tests") |
388+ | :---: | :---: | :---: | :---: | :---: | :---: |
363389
364390<!-- ALL-CONTRIBUTORS-LIST:END -->
365391
0 commit comments