Skip to content

Commit

Permalink
refactor: impl same logic as lodash.isEqualWith
Browse files Browse the repository at this point in the history
  • Loading branch information
re-taro committed Mar 24, 2024
1 parent 1c489df commit 254b60e
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 14 deletions.
18 changes: 8 additions & 10 deletions 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
Expand Down Expand Up @@ -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`
Expand Down
11 changes: 7 additions & 4 deletions 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)
Expand All @@ -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'
Expand Down
9 changes: 9 additions & 0 deletions src/utils.js
Expand Up @@ -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,
Expand All @@ -233,4 +241,5 @@ export {
getTag,
getSingleElementValue,
toSentence,
isEqualWithArraysAsSets,
}

0 comments on commit 254b60e

Please sign in to comment.