From 4179117d3df1f2cd6c7a203759b3668dcd092ac7 Mon Sep 17 00:00:00 2001 From: Nick McCurdy Date: Tue, 29 Dec 2020 20:40:05 -0500 Subject: [PATCH] fix: check equality in toHaveDisplayValue (fix #290) (#319) --- src/__tests__/to-have-display-value.js | 11 +++++++++++ src/to-have-display-value.js | 19 ++++++++----------- 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/src/__tests__/to-have-display-value.js b/src/__tests__/to-have-display-value.js index 8cae8734..05ac73e7 100644 --- a/src/__tests__/to-have-display-value.js +++ b/src/__tests__/to-have-display-value.js @@ -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...'), @@ -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(` + + `) + + expect(queryByTestId('select')).toHaveDisplayValue(1) +}) diff --git a/src/to-have-display-value.js b/src/to-have-display-value.js index bdfd2c78..eac643a9 100644 --- a/src/to-have-display-value.js +++ b/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) @@ -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 = @@ -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 -}