forked from testing-library/jest-dom
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathto-be-required.js
76 lines (66 loc) · 1.78 KB
/
to-be-required.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
import {checkHtmlElement, getTag} from './utils'
// form elements that support 'required'
const FORM_TAGS = ['select', 'textarea']
const ARIA_FORM_TAGS = ['input', 'select', 'textarea']
const UNSUPPORTED_INPUT_TYPES = [
'color',
'hidden',
'range',
'submit',
'image',
'reset',
]
const SUPPORTED_ARIA_ROLES = [
'checkbox',
'combobox',
'gridcell',
'listbox',
'radiogroup',
'spinbutton',
'textbox',
'tree',
]
function isRequiredOnFormTagsExceptInput(element) {
return FORM_TAGS.includes(getTag(element)) && element.hasAttribute('required')
}
function isRequiredOnSupportedInput(element) {
return (
getTag(element) === 'input' &&
element.hasAttribute('required') &&
((element.hasAttribute('type') &&
!UNSUPPORTED_INPUT_TYPES.includes(element.getAttribute('type'))) ||
!element.hasAttribute('type'))
)
}
function isElementRequiredByARIA(element) {
return (
element.hasAttribute('aria-required') &&
element.getAttribute('aria-required') === 'true' &&
(ARIA_FORM_TAGS.includes(getTag(element)) ||
(element.hasAttribute('role') &&
SUPPORTED_ARIA_ROLES.includes(element.getAttribute('role'))))
)
}
export function toBeRequired(element) {
checkHtmlElement(element, toBeRequired, this)
const isRequired =
isRequiredOnFormTagsExceptInput(element) ||
isRequiredOnSupportedInput(element) ||
isElementRequiredByARIA(element)
return {
pass: isRequired,
message: () => {
const is = isRequired ? 'is' : 'is not'
return [
this.utils.matcherHint(
`${this.isNot ? '.not' : ''}.toBeRequired`,
'element',
'',
),
'',
`Received element ${is} required:`,
` ${this.utils.printReceived(element.cloneNode(false))}`,
].join('\n')
},
}
}