Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(toHaveValue): Enhanced error message with type information on loose equality #219

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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