-
Notifications
You must be signed in to change notification settings - Fork 403
/
to-have-value.js
52 lines (47 loc) · 1.52 KB
/
to-have-value.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 isEqualWith from 'lodash/isEqualWith.js'
import {
checkHtmlElement,
getMessage,
getSingleElementValue,
compareArraysAsSet,
} from './utils'
export function toHaveValue(htmlElement, expectedValue) {
checkHtmlElement(htmlElement, toHaveValue, this)
if (
htmlElement.tagName.toLowerCase() === 'input' &&
['checkbox', 'radio'].includes(htmlElement.type)
) {
throw new Error(
'input with type=checkbox or type=radio cannot be used with .toHaveValue(). Use .toBeChecked() for type=checkbox or .toHaveFormValues() instead',
)
}
const receivedValue = getSingleElementValue(htmlElement)
const expectsValue = expectedValue !== undefined
let expectedTypedValue = expectedValue
let receivedTypedValue = receivedValue
if (expectedValue == receivedValue && expectedValue !== receivedValue) {
expectedTypedValue = `${expectedValue} (${typeof expectedValue})`
receivedTypedValue = `${receivedValue} (${typeof receivedValue})`
}
return {
pass: expectsValue
? isEqualWith(receivedValue, expectedValue, compareArraysAsSet)
: Boolean(receivedValue),
message: () => {
const to = this.isNot ? 'not to' : 'to'
const matcher = this.utils.matcherHint(
`${this.isNot ? '.not' : ''}.toHaveValue`,
'element',
expectedValue,
)
return getMessage(
this,
matcher,
`Expected the element ${to} have value`,
expectsValue ? expectedTypedValue : '(any)',
'Received',
receivedTypedValue,
)
},
}
}