Skip to content

Commit

Permalink
feat(toHaveValue): Enhanced error message with type information… (#219)
Browse files Browse the repository at this point in the history
* Enhanced error message of toHaveValue

* Added tests

* Refactored tests.
  • Loading branch information
maltebaer committed Mar 25, 2020
1 parent c80448f commit eb51c17
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
20 changes: 20 additions & 0 deletions src/__tests__/to-have-value.js
Expand Up @@ -124,6 +124,26 @@ describe('.toHaveValue', () => {
`)
})

test('throws with type information when the expected text input value has loose equality with received value', () => {
const {container} = render(`<input data-testid="one" value="8" />`)
const input = container.firstChild
let errorMessage
try {
expect(input).toHaveValue(8)
} catch (error) {
errorMessage = error.message
}

expect(errorMessage).toMatchInlineSnapshot(`
"<dim>expect(</><red>element</><dim>).toHaveValue(</><green>8</><dim>)</>
Expected the element to have value:
<green> 8 (number)</>
Received:
<red> 8 (string)</>"
`)
})

test('throws when using not but the expected input value does match', () => {
const {container} = render(`<input data-testid="one" value="foo" />`)
const input = container.firstChild
Expand Down
12 changes: 10 additions & 2 deletions src/to-have-value.js
Expand Up @@ -21,6 +21,14 @@ export function toHaveValue(htmlElement, expectedValue) {

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)
Expand All @@ -35,9 +43,9 @@ export function toHaveValue(htmlElement, expectedValue) {
return getMessage(
matcher,
`Expected the element ${to} have value`,
expectsValue ? expectedValue : '(any)',
expectsValue ? expectedTypedValue : '(any)',
'Received',
receivedValue,
receivedTypedValue,
)
},
}
Expand Down

0 comments on commit eb51c17

Please sign in to comment.