-
Notifications
You must be signed in to change notification settings - Fork 405
/
Copy pathto-have-errormessage.js
71 lines (62 loc) · 2.15 KB
/
to-have-errormessage.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
import {checkHtmlElement, getMessage, normalize, deprecate} from './utils'
// See aria-errormessage spec https://www.w3.org/TR/wai-aria-1.2/#aria-errormessage
export function toHaveErrorMessage(htmlElement, checkWith) {
deprecate('toHaveErrorMessage', 'Please use toHaveAccessibleErrorMessage.')
checkHtmlElement(htmlElement, toHaveErrorMessage, this)
if (
!htmlElement.hasAttribute('aria-invalid') ||
htmlElement.getAttribute('aria-invalid') === 'false'
) {
const not = this.isNot ? '.not' : ''
return {
pass: false,
message: () => {
return getMessage(
this,
this.utils.matcherHint(`${not}.toHaveErrorMessage`, 'element', ''),
`Expected the element to have invalid state indicated by`,
'aria-invalid="true"',
'Received',
htmlElement.hasAttribute('aria-invalid')
? `aria-invalid="${htmlElement.getAttribute('aria-invalid')}"`
: this.utils.printReceived(''),
)
},
}
}
const expectsErrorMessage = checkWith !== undefined
const errormessageIDRaw = htmlElement.getAttribute('aria-errormessage') || ''
const errormessageIDs = errormessageIDRaw.split(/\s+/).filter(Boolean)
let errormessage = ''
if (errormessageIDs.length > 0) {
const document = htmlElement.ownerDocument
const errormessageEls = errormessageIDs
.map(errormessageID => document.getElementById(errormessageID))
.filter(Boolean)
errormessage = normalize(
errormessageEls.map(el => el.textContent).join(' '),
)
}
return {
pass: expectsErrorMessage
? checkWith instanceof RegExp
? checkWith.test(errormessage)
: this.equals(errormessage, checkWith)
: Boolean(errormessage),
message: () => {
const to = this.isNot ? 'not to' : 'to'
return getMessage(
this,
this.utils.matcherHint(
`${this.isNot ? '.not' : ''}.toHaveErrorMessage`,
'element',
'',
),
`Expected the element ${to} have error message`,
this.utils.printExpected(checkWith),
'Received',
this.utils.printReceived(errormessage),
)
},
}
}