Skip to content

Commit

Permalink
fix: check equality in toHaveDisplayValue (fix #290) (#319)
Browse files Browse the repository at this point in the history
  • Loading branch information
nickmccurdy committed Dec 30, 2020
1 parent 2927c95 commit 4179117
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 11 deletions.
11 changes: 11 additions & 0 deletions src/__tests__/to-have-display-value.js
Expand Up @@ -11,6 +11,7 @@ test('it should work as expected', () => {
`)

expect(queryByTestId('select')).toHaveDisplayValue('Select a fruit...')
expect(queryByTestId('select')).not.toHaveDisplayValue('Select')
expect(queryByTestId('select')).not.toHaveDisplayValue('Banana')
expect(() =>
expect(queryByTestId('select')).not.toHaveDisplayValue('Select a fruit...'),
Expand Down Expand Up @@ -151,3 +152,13 @@ test('it should throw if element is not valid', () => {
`".toHaveDisplayValue() currently does not support input[type=\\"checkbox\\"], try with another matcher instead."`,
)
})

test('it should work with numbers', () => {
const {queryByTestId} = render(`
<select data-testid="select">
<option value="">1</option>
</select>
`)

expect(queryByTestId('select')).toHaveDisplayValue(1)
})
19 changes: 8 additions & 11 deletions src/to-have-display-value.js
@@ -1,4 +1,4 @@
import {matches, checkHtmlElement, getMessage} from './utils'
import {checkHtmlElement, getMessage} from './utils'

export function toHaveDisplayValue(htmlElement, expectedValue) {
checkHtmlElement(htmlElement, toHaveDisplayValue, this)
Expand All @@ -18,10 +18,13 @@ export function toHaveDisplayValue(htmlElement, expectedValue) {

const values = getValues(tagName, htmlElement)
const expectedValues = getExpectedValues(expectedValue)
const numberOfMatchesWithValues = getNumberOfMatchesBetweenArrays(
values,
expectedValues,
)
const numberOfMatchesWithValues = expectedValues.filter(expected =>
values.some(value =>
expected instanceof RegExp
? expected.test(value)
: this.equals(value, String(expected)),
),
).length

const matchedWithAllValues = numberOfMatchesWithValues === values.length
const matchedWithAllExpectedValues =
Expand Down Expand Up @@ -56,9 +59,3 @@ function getValues(tagName, htmlElement) {
function getExpectedValues(expectedValue) {
return expectedValue instanceof Array ? expectedValue : [expectedValue]
}

function getNumberOfMatchesBetweenArrays(arrayBase, array) {
return array.filter(
expected => arrayBase.filter(value => matches(value, expected)).length,
).length
}

0 comments on commit 4179117

Please sign in to comment.