Skip to content

Commit eb51c17

Browse files
authored
feat(toHaveValue): Enhanced error message with type information… (#219)
* Enhanced error message of toHaveValue * Added tests * Refactored tests.
1 parent c80448f commit eb51c17

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

src/__tests__/to-have-value.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,26 @@ describe('.toHaveValue', () => {
124124
`)
125125
})
126126

127+
test('throws with type information when the expected text input value has loose equality with received value', () => {
128+
const {container} = render(`<input data-testid="one" value="8" />`)
129+
const input = container.firstChild
130+
let errorMessage
131+
try {
132+
expect(input).toHaveValue(8)
133+
} catch (error) {
134+
errorMessage = error.message
135+
}
136+
137+
expect(errorMessage).toMatchInlineSnapshot(`
138+
"<dim>expect(</><red>element</><dim>).toHaveValue(</><green>8</><dim>)</>
139+
140+
Expected the element to have value:
141+
<green> 8 (number)</>
142+
Received:
143+
<red> 8 (string)</>"
144+
`)
145+
})
146+
127147
test('throws when using not but the expected input value does match', () => {
128148
const {container} = render(`<input data-testid="one" value="foo" />`)
129149
const input = container.firstChild

src/to-have-value.js

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,14 @@ export function toHaveValue(htmlElement, expectedValue) {
2121

2222
const receivedValue = getSingleElementValue(htmlElement)
2323
const expectsValue = expectedValue !== undefined
24+
25+
let expectedTypedValue = expectedValue
26+
let receivedTypedValue = receivedValue
27+
if (expectedValue == receivedValue && expectedValue !== receivedValue) {
28+
expectedTypedValue = `${expectedValue} (${typeof expectedValue})`
29+
receivedTypedValue = `${receivedValue} (${typeof receivedValue})`
30+
}
31+
2432
return {
2533
pass: expectsValue
2634
? isEqualWith(receivedValue, expectedValue, compareArraysAsSet)
@@ -35,9 +43,9 @@ export function toHaveValue(htmlElement, expectedValue) {
3543
return getMessage(
3644
matcher,
3745
`Expected the element ${to} have value`,
38-
expectsValue ? expectedValue : '(any)',
46+
expectsValue ? expectedTypedValue : '(any)',
3947
'Received',
40-
receivedValue,
48+
receivedTypedValue,
4149
)
4250
},
4351
}

0 commit comments

Comments
 (0)