16
16
[ ![ downloads] [ downloads-badge ]] [ npmtrends ]
17
17
[ ![ MIT License] [ license-badge ]] [ license ]
18
18
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 )
20
20
[ ![ PRs Welcome] [ prs-badge ]] [ prs ]
21
21
[ ![ Code of Conduct] [ coc-badge ]] [ coc ]
22
22
@@ -86,18 +86,18 @@ test('Fetch makes an API call and displays the greeting when load-greeting is cl
86
86
}),
87
87
)
88
88
const url = ' /greeting'
89
- const {queryByTestId , container } = render (< Fetch url= {url} / > )
89
+ const {getByTestId , container } = render (< Fetch url= {url} / > )
90
90
91
91
// Act
92
- Simulate .click (queryByTestId (' load-greeting' ))
92
+ Simulate .click (getByTestId (' load-greeting' ))
93
93
94
94
// let's wait for our mocked `get` request promise to resolve
95
95
await flushPromises ()
96
96
97
97
// Assert
98
98
expect (axiosMock .get ).toHaveBeenCalledTimes (1 )
99
99
expect (axiosMock .get ).toHaveBeenCalledWith (url)
100
- expect (queryByTestId (' greeting-text' ).textContent ).toBe (' hello there' )
100
+ expect (getByTestId (' greeting-text' ).textContent ).toBe (' hello there' )
101
101
expect (container .firstChild ).toMatchSnapshot ()
102
102
})
103
103
```
@@ -146,18 +146,34 @@ unmount()
146
146
// your component has been unmounted and now: container.innerHTML === ''
147
147
```
148
148
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
+
149
161
#### ` queryByTestId `
150
162
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.
153
167
154
168
``` 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 ()
156
172
```
157
173
158
174
## More on ` data-testid ` s
159
175
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 `
161
177
attributes to identify individual elements in your rendered component. This is
162
178
one of the practices this library is intended to encourage.
163
179
@@ -186,14 +202,14 @@ prefer to update the props of a rendered component in your test, the easiest
186
202
way to do that is:
187
203
188
204
``` 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' )
191
207
192
208
// re-render the same component with different props
193
209
// but pass the same container in the options argument.
194
210
// which will cause a re-render of the same instance (normal React behavior).
195
211
render (< NumberDisplay number= {2 } / > , {container})
196
- expect (queryByTestId (' number-display' ).textContent ).toBe (' 2' )
212
+ expect (getByTestId (' number-display' ).textContent ).toBe (' 2' )
197
213
```
198
214
199
215
[ 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', () => {
219
235
})
220
236
221
237
test (' you can mock things with jest.mock' , () => {
222
- const {queryByTestId } = render (< HiddenMessage initialShow= {true } / > )
238
+ const {getByTestId , queryByTestId } = render (
239
+ < HiddenMessage initialShow= {true } / > ,
240
+ )
223
241
expect (queryByTestId (' hidden-message' )).toBeTruthy () // we just care it exists
224
242
// hide the message
225
- Simulate .click (queryByTestId (' toggle-message' ))
243
+ Simulate .click (getByTestId (' toggle-message' ))
226
244
// in the real world, the CSSTransition component would take some time
227
245
// before finishing the animation which would actually hide the message.
228
246
// 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
230
248
})
231
249
```
232
250
@@ -247,6 +265,14 @@ something more
247
265
Learn more about how Jest mocks work from my blog post:
248
266
[ "But really, what is a JavaScript mock?"] ( https://blog.kentcdodds.com/but-really-what-is-a-javascript-mock-10d060966f7d )
249
267
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
+
250
276
** I don't want to use ` data-testid ` attributes for everything. Do I have to?**
251
277
252
278
Definitely 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:
286
312
< li data- testid= {` item-${ item .id } ` }> {item .text }< / li>
287
313
```
288
314
289
- And then you could use the ` queryByTestId ` :
315
+ And then you could use the ` getByTestId ` utility :
290
316
291
317
``` javascript
292
318
const items = [
293
319
/* your items */
294
320
]
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 } ` )
297
323
```
298
324
299
325
** What about enzyme is "bloated with complexity and features" and "encourage poor testing
300
- practices"**
326
+ practices"? **
301
327
302
328
Most of the damaging features have to do with encouraging testing implementation
303
329
details. Primarily, these are
@@ -358,8 +384,8 @@ Thanks goes to these people ([emoji key][emojis]):
358
384
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
359
385
360
386
<!-- 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
+ | :---: | :---: | :---: | :---: | :---: | :---: |
363
389
364
390
<!-- ALL-CONTRIBUTORS-LIST:END -->
365
391
0 commit comments