-
Notifications
You must be signed in to change notification settings - Fork 405
/
Copy pathto-have-attribute.js
52 lines (49 loc) · 1.66 KB
/
to-have-attribute.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
import {checkHtmlElement, getMessage} from './utils'
function printAttribute(stringify, name, value) {
return value === undefined ? name : `${name}=${stringify(value)}`
}
function getAttributeComment(stringify, name, value) {
return value === undefined
? `element.hasAttribute(${stringify(name)})`
: `element.getAttribute(${stringify(name)}) === ${stringify(value)}`
}
export function toHaveAttribute(htmlElement, name, expectedValue) {
checkHtmlElement(htmlElement, toHaveAttribute, this)
const isExpectedValuePresent = expectedValue !== undefined
const hasAttribute = htmlElement.hasAttribute(name)
const receivedValue = htmlElement.getAttribute(name)
return {
pass: isExpectedValuePresent
? hasAttribute && this.equals(receivedValue, expectedValue)
: hasAttribute,
message: () => {
const to = this.isNot ? 'not to' : 'to'
const receivedAttribute = hasAttribute
? printAttribute(this.utils.stringify, name, receivedValue)
: null
const matcher = this.utils.matcherHint(
`${this.isNot ? '.not' : ''}.toHaveAttribute`,
'element',
this.utils.printExpected(name),
{
secondArgument: isExpectedValuePresent
? this.utils.printExpected(expectedValue)
: undefined,
comment: getAttributeComment(
this.utils.stringify,
name,
expectedValue,
),
},
)
return getMessage(
this,
matcher,
`Expected the element ${to} have attribute`,
printAttribute(this.utils.stringify, name, expectedValue),
'Received',
receivedAttribute,
)
},
}
}