forked from testing-library/dom-testing-library
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathelement-queries.js
579 lines (525 loc) · 18.9 KB
/
element-queries.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
import 'jest-dom/extend-expect'
import {configure} from '../config'
import {render, renderIntoDocument} from './helpers/test-utils'
import document from './helpers/document'
beforeEach(() => {
document.defaultView.Cypress = null
})
test('query can return null', () => {
const {
queryByLabelText,
queryBySelectText,
queryByPlaceholderText,
queryByText,
queryByTestId,
queryByAltText,
} = render('<div />')
expect(queryByTestId('LucyRicardo')).toBeNull()
expect(queryByLabelText('LucyRicardo')).toBeNull()
expect(queryBySelectText('LucyRicardo')).toBeNull()
expect(queryByPlaceholderText('LucyRicardo')).toBeNull()
expect(queryByText('LucyRicardo')).toBeNull()
expect(queryByAltText('LucyRicardo')).toBeNull()
})
test('get throws a useful error message', () => {
const {
getByLabelText,
getBySelectText,
getByPlaceholderText,
getByText,
getByTestId,
getByAltText,
getByTitle,
getByValue,
getByRole,
} = render('<div />')
expect(() => getByLabelText('LucyRicardo')).toThrowErrorMatchingSnapshot()
expect(() => getBySelectText('LucyRicardo')).toThrowErrorMatchingSnapshot()
expect(() =>
getByPlaceholderText('LucyRicardo'),
).toThrowErrorMatchingSnapshot()
expect(() => getByText('LucyRicardo')).toThrowErrorMatchingSnapshot()
expect(() => getByTestId('LucyRicardo')).toThrowErrorMatchingSnapshot()
expect(() => getByAltText('LucyRicardo')).toThrowErrorMatchingSnapshot()
expect(() => getByTitle('LucyRicardo')).toThrowErrorMatchingSnapshot()
expect(() => getByValue('LucyRicardo')).toThrowErrorMatchingSnapshot()
expect(() => getByRole('LucyRicardo')).toThrowErrorMatchingSnapshot()
})
test('can get elements by matching their text content', () => {
const {queryByText} = render(`
<div>
<span>Currently showing</span>
<span>
Step
1
of 4
</span>
</div>
`)
expect(queryByText('Currently showing')).toBeTruthy()
expect(queryByText('Step 1 of 4')).toBeTruthy()
})
test('can get elements by matching their text across adjacent text nodes', () => {
const textDiv = document.createElement('div')
const textNodeContent = ['£', '24', '.', '99']
textNodeContent
.map(text => document.createTextNode(text))
.forEach(textNode => textDiv.appendChild(textNode))
const {container, queryByText} = render('<div />')
container.appendChild(textDiv)
expect(queryByText('£24.99')).toBeTruthy()
})
test('matches case with RegExp matcher', () => {
const {queryByText} = render(`
<span>STEP 1 of 4</span>
`)
expect(queryByText(/STEP 1 of 4/)).toBeTruthy()
expect(queryByText(/Step 1 of 4/)).not.toBeTruthy()
})
test('can get form controls by label text', () => {
const {getByLabelText} = render(`
<div>
<label>
1st<input id="first-id" />
</label>
<div>
<label for="second-id">2nd</label>
<input id="second-id" />
</div>
<div>
<label id="third-label">3rd</label>
<input aria-labelledby="third-label" id="third-id" />
</div>
<div>
<label for="fourth.id">4th</label>
<input id="fourth.id" />
</div>
<div>
<div>
<label id="fifth-label-one">5th one</label>
<label id="fifth-label-two">5th two</label>
<input aria-labelledby="fifth-label-one fifth-label-two" id="fifth-id" />
</div>
</div>
`)
expect(getByLabelText('1st').id).toBe('first-id')
expect(getByLabelText('2nd').id).toBe('second-id')
expect(getByLabelText('3rd').id).toBe('third-id')
expect(getByLabelText('4th').id).toBe('fourth.id')
expect(getByLabelText('5th one').id).toBe('fifth-id')
expect(getByLabelText('5th two').id).toBe('fifth-id')
})
test('can get elements labelled with aria-labelledby attribute', () => {
const {getByLabelText, getAllByLabelText} = render(`
<div>
<h1 id="content-header">The Gettysburg Address</h1>
<main id="sibling-of-content-header" aria-labelledby="content-header">
<section aria-labelledby="content-header section-one-header" id="section-one">
<h2 id="section-one-header">Section One</h2>
<p>Four score and seven years ago, ...</p>
</section>
</main>
<p>The Gettysburg Address</p>
</div>
`)
const result = getAllByLabelText('The Gettysburg Address').map(el => el.id)
expect(result).toHaveLength(2)
expect(result).toEqual(
expect.arrayContaining(['sibling-of-content-header', 'section-one']),
)
expect(getByLabelText('Section One').id).toBe('section-one')
})
test('get can get form controls by placeholder', () => {
const {getByPlaceholderText} = render(`
<input id="username-id" placeholder="username" />,
`)
expect(getByPlaceholderText('username').id).toBe('username-id')
})
test('label with no form control', () => {
const {getByLabelText, queryByLabelText} = render(`<label>All alone</label>`)
expect(queryByLabelText(/alone/)).toBeNull()
expect(() => getByLabelText(/alone/)).toThrowErrorMatchingSnapshot()
})
test('totally empty label', () => {
const {getByLabelText, queryByLabelText} = render(`<label />`)
expect(queryByLabelText('')).toBeNull()
expect(() => getByLabelText('')).toThrowErrorMatchingSnapshot()
})
test('getByLabelText with aria-label', () => {
// not recommended normally, but supported for completeness
const {queryByLabelText} = render(`<input aria-label="batman" />`)
expect(queryByLabelText(/bat/)).toBeTruthy()
})
test('get element by its alt text', () => {
const {getByAltText} = render(`
<div>
<input data-info="no alt here" />
<img alt="finding nemo poster" src="/finding-nemo.png" />
</div>,
`)
expect(getByAltText(/fin.*nem.*poster$/i).src).toContain('/finding-nemo.png')
})
test('query/get element by its title', () => {
const {getByTitle, queryByTitle} = render(`
<div>
<span title="Ignore this" id="1"/>
<span title="Delete" id="2"/>
<span title="Ignore this as well" id="3"/>
</div>
`)
expect(getByTitle('Delete').id).toEqual('2')
expect(queryByTitle('Delete').id).toEqual('2')
expect(queryByTitle('Del', {exact: false}).id).toEqual('2')
})
test('query/get title element of SVG', () => {
const {getByTitle, queryByTitle} = render(`
<div>
<svg>
<title id="svg-title">Close</title>
<g>
<path />
</g>
</svg>
</div>
`)
expect(getByTitle('Close').id).toEqual('svg-title')
expect(queryByTitle('Close').id).toEqual('svg-title')
})
test('query/get element by its value', () => {
const {getByValue, queryByValue} = render(`
<div>
<input placeholder="name" type="text"/>
<input placeholder="lastname" type="text" value="Norris"/>
<input placeholder="email" type="text"/>
</div>
`)
expect(getByValue('Norris').placeholder).toEqual('lastname')
expect(queryByValue('Norris').placeholder).toEqual('lastname')
})
test('query/get select by text with the default option selected', () => {
const {getBySelectText, queryBySelectText} = render(`
<select id="state-select">
<option value="">State</option>
<option value="AL">Alabama</option>
<option value="AK" >Alaska</option>
<option value="AZ">Arizona</option>
</select>
`)
expect(getBySelectText('State').id).toEqual('state-select')
expect(queryBySelectText('State').id).toEqual('state-select')
})
test('query/get select by text with one option selected', () => {
const {getBySelectText, queryBySelectText} = render(`
<select id="state-select">
<option value="">State</option>
<option value="AL">Alabama</option>
<option selected value="AK" >Alaska</option>
<option value="AZ">Arizona</option>
</select>
`)
expect(getBySelectText('Alaska').id).toEqual('state-select')
expect(queryBySelectText('Alaska').id).toEqual('state-select')
})
test('query/get select by text with multiple options selected', () => {
const {getBySelectText, queryBySelectText} = render(`
<select multiple id="state-select">
<option value="">State</option>
<option selected value="AL">Alabama</option>
<option selected value="AK" >Alaska</option>
<option value="AZ">Arizona</option>
</select>
`)
expect(getBySelectText('Alabama').id).toEqual('state-select')
expect(queryBySelectText('Alaska').id).toEqual('state-select')
})
describe('query by test id', () => {
test('can get elements by test id', () => {
const {queryByTestId} = render(`<div data-testid="firstName"></div>`)
expect(queryByTestId('firstName')).toBeTruthy()
expect(queryByTestId(/first/)).toBeTruthy()
expect(queryByTestId(testid => testid === 'firstName')).toBeTruthy()
// match should be exact, case-sensitive
expect(queryByTestId('firstname')).not.toBeTruthy()
expect(queryByTestId('first')).not.toBeTruthy()
expect(queryByTestId('firstNamePlusMore')).not.toBeTruthy()
expect(queryByTestId('first-name')).not.toBeTruthy()
})
test('can override test id attribute', () => {
const {queryByTestId} = render(`<div data-my-test-id="theTestId"></div>`)
configure({testIdAttribute: 'data-my-test-id'})
expect(queryByTestId('theTestId')).toBeTruthy()
configure({testIdAttribute: 'something-else'})
expect(queryByTestId('theTestId')).toBeFalsy()
})
afterEach(() => {
// Restore the default test id attribute
// even if these tests failed
configure({testIdAttribute: 'data-testid'})
})
})
test('getAll* matchers return an array', () => {
const {
getAllByAltText,
getAllByTestId,
getAllByLabelText,
getAllBySelectText,
getAllByPlaceholderText,
getAllByText,
getAllByRole,
} = render(`
<div role="container">
<img
data-testid="poster"
alt="finding nemo poster"
src="/finding-nemo.png" />
<img
data-testid="poster"
alt="finding dory poster"
src="/finding-dory.png" />
<img
data-testid="poster"
alt="jumanji poster"
src="/jumanji.png" />
<p>Where to next?</p>
<label for="username">User Name</label>
<input id="username" placeholder="Dwayne 'The Rock' Johnson" />
<select>
<option value="">German cars</option>
<option value="volvo">BMW</option>
<option value="audi">Audi</option>
</select>
<select>
<option value="">Japanese cars</option>
<option value="volvo">Toyota</option>
<option value="audi">Honda</option>
</select>
</div>,
`)
expect(getAllByAltText(/finding.*poster$/i)).toHaveLength(2)
expect(getAllByAltText(/jumanji/)).toHaveLength(1)
expect(getAllByTestId('poster')).toHaveLength(3)
expect(getAllByPlaceholderText(/The Rock/)).toHaveLength(1)
expect(getAllByLabelText('User Name')).toHaveLength(1)
expect(getAllBySelectText('Japanese cars')).toHaveLength(1)
expect(getAllBySelectText(/cars$/)).toHaveLength(2)
expect(getAllByText(/^where/i)).toHaveLength(1)
expect(getAllByRole(/container/i)).toHaveLength(1)
})
test('getAll* matchers throw for 0 matches', () => {
const {
getAllByAltText,
getAllByTestId,
getAllByLabelText,
getAllBySelectText,
getAllByPlaceholderText,
getAllByText,
getAllByRole,
} = render(`
<div role="container">
<label>No Matches Please</label>
</div>,
`)
expect(() => getAllByTestId('nope')).toThrow()
expect(() => getAllByTestId('abc')).toThrow()
expect(() => getAllByAltText('nope')).toThrow()
expect(() => getAllByLabelText('nope')).toThrow()
expect(() => getAllByLabelText('no matches please')).toThrow()
expect(() => getAllBySelectText('nope')).toThrow()
expect(() => getAllByPlaceholderText('nope')).toThrow()
expect(() => getAllByText('nope')).toThrow()
expect(() => getAllByRole('nope')).toThrow()
})
test('queryAll* matchers return an array for 0 matches', () => {
const {
queryAllByAltText,
queryAllByTestId,
queryAllByLabelText,
queryAllBySelectText,
queryAllByPlaceholderText,
queryAllByText,
queryAllByRole,
} = render(`
<div>
</div>,
`)
expect(queryAllByTestId('nope')).toHaveLength(0)
expect(queryAllByAltText('nope')).toHaveLength(0)
expect(queryAllByLabelText('nope')).toHaveLength(0)
expect(queryAllBySelectText('nope')).toHaveLength(0)
expect(queryAllByPlaceholderText('nope')).toHaveLength(0)
expect(queryAllByText('nope')).toHaveLength(0)
expect(queryAllByRole('nope')).toHaveLength(0)
})
test('using jest helpers to assert element states', () => {
const {queryByTestId} = render(`<span data-testid="count-value">2</span>`)
// other ways to assert your test cases, but you don't need all of them.
expect(queryByTestId('count-value')).toBeTruthy()
expect(queryByTestId('count-value1')).not.toBeTruthy()
expect(queryByTestId('count-value')).toHaveTextContent('2')
expect(queryByTestId('count-value')).not.toHaveTextContent('21')
expect(() =>
expect(queryByTestId('count-value2')).toHaveTextContent('2'),
).toThrowError()
// negative test cases wrapped in throwError assertions for coverage.
expect(() =>
expect(queryByTestId('count-value')).not.toBeTruthy(),
).toThrowError()
expect(() =>
expect(queryByTestId('count-value1')).toBeTruthy(),
).toThrowError()
expect(() =>
expect(queryByTestId('count-value')).toHaveTextContent('3'),
).toThrowError()
expect(() =>
expect(queryByTestId('count-value')).not.toHaveTextContent('2'),
).toThrowError()
})
test('using jest helpers to check element attributes', () => {
const {getByTestId} = render(`
<button data-testid="ok-button" type="submit" disabled>
OK
</button>
`)
expect(getByTestId('ok-button')).toHaveAttribute('disabled')
expect(getByTestId('ok-button')).toHaveAttribute('type')
expect(getByTestId('ok-button')).not.toHaveAttribute('class')
expect(getByTestId('ok-button')).toHaveAttribute('type', 'submit')
expect(getByTestId('ok-button')).not.toHaveAttribute('type', 'button')
expect(() =>
expect(getByTestId('ok-button')).not.toHaveAttribute('disabled'),
).toThrowError()
expect(() =>
expect(getByTestId('ok-button')).not.toHaveAttribute('type'),
).toThrowError()
expect(() =>
expect(getByTestId('ok-button')).toHaveAttribute('class'),
).toThrowError()
expect(() =>
expect(getByTestId('ok-button')).not.toHaveAttribute('type', 'submit'),
).toThrowError()
expect(() =>
expect(getByTestId('ok-button')).toHaveAttribute('type', 'button'),
).toThrowError()
})
test('using jest helpers to check element class names', () => {
const {getByTestId} = render(`
<div>
<button data-testid="delete-button" class="btn extra btn-danger">
Delete item
</button>
<button data-testid="cancel-button">
Cancel
</button>
</div>
`)
expect(getByTestId('delete-button')).toHaveClass('btn')
expect(getByTestId('delete-button')).toHaveClass('btn-danger')
expect(getByTestId('delete-button')).toHaveClass('extra')
expect(getByTestId('delete-button')).not.toHaveClass('xtra')
expect(getByTestId('delete-button')).toHaveClass('btn btn-danger')
expect(getByTestId('delete-button')).not.toHaveClass('btn-link')
expect(getByTestId('cancel-button')).not.toHaveClass('btn-danger')
expect(() =>
expect(getByTestId('delete-button')).not.toHaveClass('btn'),
).toThrowError()
expect(() =>
expect(getByTestId('delete-button')).not.toHaveClass('btn-danger'),
).toThrowError()
expect(() =>
expect(getByTestId('delete-button')).not.toHaveClass('extra'),
).toThrowError()
expect(() =>
expect(getByTestId('delete-button')).toHaveClass('xtra'),
).toThrowError()
expect(() =>
expect(getByTestId('delete-button')).not.toHaveClass('btn btn-danger'),
).toThrowError()
expect(() =>
expect(getByTestId('delete-button')).toHaveClass('btn-link'),
).toThrowError()
expect(() =>
expect(getByTestId('cancel-button')).toHaveClass('btn-danger'),
).toThrowError()
})
test('using jest helpers to check element role', () => {
const {getByRole} = render(`
<div role="dialog">
<span>Contents</span>
</div>
`)
expect(getByRole('dialog')).toHaveTextContent('Contents')
})
test('test the debug helper prints the dom state here', () => {
const originalDebugPrintLimit = process.env.DEBUG_PRINT_LIMIT
const Large = `<div>
${Array.from({length: 7000}, (v, key) => key).map(() => {
return `<div data-testid="debugging" data-otherid="debugging">
Hello World!
</div>`
})}
</div>`
const {getByText} = renderIntoDocument(Large) // render large DOM which exceeds 7000 limit
expect(() => expect(getByText('not present')).toBeTruthy()).toThrowError()
const Hello = `<div data-testid="debugging" data-otherid="debugging">
Hello World!
</div>`
const {getByTestId} = renderIntoDocument(Hello)
process.env.DEBUG_PRINT_LIMIT = 5 // user should see `...`
expect(() => expect(getByTestId('not present')).toBeTruthy()).toThrowError(
/\.\.\.$/,
)
const {getByLabelText} = renderIntoDocument(Hello)
process.env.DEBUG_PRINT_LIMIT = 10000 // user shouldn't see `...`
expect(() =>
expect(getByLabelText('not present')).toBeTruthy(/^((?!\.\.\.).)*$/),
).toThrowError()
//all good replacing it with old value
process.env.DEBUG_PRINT_LIMIT = originalDebugPrintLimit
})
test('get throws a useful error message without DOM in Cypress', () => {
document.defaultView.Cypress = {}
const {
getByLabelText,
getBySelectText,
getByPlaceholderText,
getByText,
getByTestId,
getByAltText,
getByTitle,
getByValue,
} = render('<div />')
expect(() => getByLabelText('LucyRicardo')).toThrowErrorMatchingSnapshot()
expect(() => getBySelectText('LucyRicardo')).toThrowErrorMatchingSnapshot()
expect(() =>
getByPlaceholderText('LucyRicardo'),
).toThrowErrorMatchingSnapshot()
expect(() => getByText('LucyRicardo')).toThrowErrorMatchingSnapshot()
expect(() => getByTestId('LucyRicardo')).toThrowErrorMatchingSnapshot()
expect(() => getByAltText('LucyRicardo')).toThrowErrorMatchingSnapshot()
expect(() => getByTitle('LucyRicardo')).toThrowErrorMatchingSnapshot()
expect(() => getByValue('LucyRicardo')).toThrowErrorMatchingSnapshot()
})
test('getByText ignores script tags by default', () => {
const {getAllByText} = render(
'<script>Hello</script><div>Hello</div><style>.Hello{}</style>',
)
const divOnly = getAllByText(/hello/i)
expect(divOnly).toHaveLength(1)
expect(divOnly[0].tagName).toBe('DIV')
const noScript = getAllByText(/hello/i, {ignore: 'script'})
expect(noScript[0].tagName).toBe('DIV')
expect(noScript[1].tagName).toBe('STYLE')
expect(noScript).toHaveLength(2)
expect(getAllByText(/hello/i, {ignore: false})).toHaveLength(3)
})
test('get element by its dynamically assigned value', () => {
const {getByValue, queryByValue, getByTestId} = renderIntoDocument(`
<div>
<input placeholder="name" type="text" data-testid="name" />
</div>
`)
getByTestId('name').value = 'Norris'
expect(getByValue('Norris').placeholder).toEqual('name')
expect(queryByValue('Norris').placeholder).toEqual('name')
})
/* eslint jsx-a11y/label-has-for:0 */