From 254b60efdab82ce368e6cb17fcac25abe4575cad Mon Sep 17 00:00:00 2001 From: Rintaro Itokawa Date: Sun, 24 Mar 2024 21:49:55 +0900 Subject: [PATCH] refactor: impl same logic as lodash.isEqualWith --- src/to-have-form-values.js | 18 ++++++++---------- src/to-have-value.js | 11 +++++++---- src/utils.js | 9 +++++++++ 3 files changed, 24 insertions(+), 14 deletions(-) diff --git a/src/to-have-form-values.js b/src/to-have-form-values.js index 9db8665..adeff37 100644 --- a/src/to-have-form-values.js +++ b/src/to-have-form-values.js @@ -1,5 +1,9 @@ import escape from 'css.escape' -import {checkHtmlElement, getSingleElementValue} from './utils' +import { + checkHtmlElement, + getSingleElementValue, + isEqualWithArraysAsSets, +} from './utils' // Returns the combined value of several elements that have the same name // e.g. radio buttons or groups of checkboxes @@ -63,15 +67,9 @@ export function toHaveFormValues(formElement, expectedValues) { } const formValues = getAllFormValues(formElement) return { - pass: Object.entries(expectedValues).every(([name, expectedValue]) => { - if (Array.isArray(formValues[name]) && Array.isArray(expectedValue)) { - return [...new Set(formValues[name])].every(v => - new Set(expectedValue).has(v), - ) - } else { - return formValues[name] === expectedValue - } - }), + pass: Object.entries(expectedValues).every(([name, expectedValue]) => + isEqualWithArraysAsSets(formValues[name], expectedValue), + ), message: () => { const to = this.isNot ? 'not to' : 'to' const matcher = `${this.isNot ? '.not' : ''}.toHaveFormValues` diff --git a/src/to-have-value.js b/src/to-have-value.js index cfe8e6b..121a41f 100644 --- a/src/to-have-value.js +++ b/src/to-have-value.js @@ -1,4 +1,9 @@ -import {checkHtmlElement, getMessage, getSingleElementValue} from './utils' +import { + checkHtmlElement, + getMessage, + getSingleElementValue, + isEqualWithArraysAsSets, +} from './utils' export function toHaveValue(htmlElement, expectedValue) { checkHtmlElement(htmlElement, toHaveValue, this) @@ -24,9 +29,7 @@ export function toHaveValue(htmlElement, expectedValue) { return { pass: expectsValue - ? Array.isArray(receivedValue) && Array.isArray(expectedValue) - ? [...new Set(receivedValue)].every(v => new Set(expectedValue).has(v)) - : receivedValue === expectedValue + ? isEqualWithArraysAsSets(receivedValue, expectedValue) : Boolean(receivedValue), message: () => { const to = this.isNot ? 'not to' : 'to' diff --git a/src/utils.js b/src/utils.js index 673f747..5ef8afd 100644 --- a/src/utils.js +++ b/src/utils.js @@ -220,6 +220,14 @@ function toSentence( ) } +function isEqualWithArraysAsSets(arr1, arr2) { + if (Array.isArray(arr1) && Array.isArray(arr2)) { + return [...new Set(arr1)].every(v => new Set(arr2).has(v)) + } else { + return arr1 === arr2 + } +} + export { HtmlElementTypeError, NodeTypeError, @@ -233,4 +241,5 @@ export { getTag, getSingleElementValue, toSentence, + isEqualWithArraysAsSets, }