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: suggest close matches using Levenshtein distance [POC] #836

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from 3 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
84 changes: 84 additions & 0 deletions src/__tests__/close-matches.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import {
calculateLevenshteinDistance,
getCloseMatchesByAttribute,
} from '../close-matches'
import {render} from './helpers/test-utils'

describe('calculateLevenshteinDistance', () => {
test.each([
['', '', 0],
['hello', 'hello', 0],
['greeting', 'greeting', 0],
['react testing library', 'react testing library', 0],
['hello', 'hellow', 1],
['greetimg', 'greeting', 1],
['submit', 'sbmit', 1],
['cance', 'cancel', 1],
['doug', 'dog', 1],
['dogs and cats', 'dogs and cat', 1],
['uncool-div', '12cool-div', 2],
['dogs and cats', 'dogs, cats', 4],
['greeting', 'greetings traveler', 10],
['react testing library', '', 21],
['react testing library', 'y', 20],
['react testing library', 'ty', 19],
['react testing library', 'tary', 17],
['react testing library', 'trary', 16],
['react testing library', 'tlibrary', 13],
['react testing library', 'react testing', 8],
['library', 'testing', 7],
['react library', 'react testing', 7],
[
'The more your tests resemble the way your software is used, the more confidence they can give you.',
'The less your tests resemble the way your software is used, the less confidence they can give you.',
8,
],
])('distance between "%s" and "%s" is %i', (text1, text2, expected) => {
expect(calculateLevenshteinDistance(text1, text2)).toBe(expected)
})
})

describe('getCloseMatchesByAttribute', () => {
test('should return all closest matches', () => {
const {container} = render(`
<div data-testid="The slow brown fox jumps over the lazy dog"></div>
<div data-testid="The rapid brown fox jumps over the lazy dog"></div>
<div data-testid="The quick black fox jumps over the lazy dog"></div>
<div data-testid="The quick brown meerkat jumps over the lazy dog"></div>
<div data-testid="The quick brown fox flies over the lazy dog"></div>
`)
expect(
getCloseMatchesByAttribute(
'data-testid',
container,
'The quick brown fox jumps over the lazy dog',
),
).toEqual([
'The quick black fox jumps over the lazy dog',
'The quick brown fox flies over the lazy dog',
])
})

test('should ignore matches that are too distant', () => {
const {container} = render(`
<div data-testid="very-cool-div"></div>
<div data-testid="too-diferent-to-match"></div>
<div data-testid="not-even-close"></div>
`)
expect(
getCloseMatchesByAttribute('data-testid', container, 'normal-div'),
).toEqual([])
})

test('should ignore duplicated matches', () => {
const {container} = render(`
<div data-testid="lazy dog"></div>
<div data-testid="lazy dog"></div>
<div data-testid="lazy dog"></div>
<div data-testid="energetic dog"></div>
`)
expect(
getCloseMatchesByAttribute('data-testid', container, 'happy dog'),
).toEqual(['lazy dog'])
})
})
39 changes: 39 additions & 0 deletions src/__tests__/element-queries.js
Original file line number Diff line number Diff line change
Expand Up @@ -1273,3 +1273,42 @@ it(`should get element by it's label when there are elements with same text`, ()
`)
expect(getByLabelText('test 1')).toBeInTheDocument()
})

test('returns closest match when computeCloseMatches = true', () => {
const {getByTestId} = render(`
<div>
<div data-testid="cat-dog"></div>
<div data-testid="meerkat"></div>
<div data-testid="tamandua"></div>
</div>`)

expect(() => getByTestId('meercat', {computeCloseMatches: true}))
.toThrowErrorMatchingInlineSnapshot(`
"Unable to find an element by: [data-testid="meercat"]. Did you mean one of the following?
meerkat

<div>


<div>


<div
data-testid="cat-dog"
/>


<div
data-testid="meerkat"
/>


<div
data-testid="tamandua"
/>


</div>
</div>"
`)
})
86 changes: 86 additions & 0 deletions src/close-matches.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import {makeNormalizer} from './matches'

const initializeDpTable = (rows, columns) => {
const dp = Array(rows + 1)
.fill()
.map(() => Array(columns + 1).fill())

// fill rows
for (let i = 0; i <= rows; i++) {
dp[i][0] = i
}

// fill columns
for (let i = 0; i <= columns; i++) {
dp[0][i] = i
}
return dp
}

export const calculateLevenshteinDistance = (text1, text2) => {
nickmccurdy marked this conversation as resolved.
Show resolved Hide resolved
const dp = initializeDpTable(text1.length, text2.length)

for (let row = 1; row < dp.length; row++) {
for (let column = 1; column < dp[row].length; column++) {
if (text1[row - 1] === text2[column - 1]) {
dp[row][column] = dp[row - 1][column - 1]
} else {
dp[row][column] =
Math.min(
dp[row - 1][column - 1],
dp[row][column - 1],
dp[row - 1][column],
) + 1
}
}
}
return dp[text1.length][text2.length]
}

const MAX_LEVENSHTEIN_DISTANCE = 4

export const getCloseMatchesByAttribute = (
attribute,
container,
searchText,
{collapseWhitespace, trim, normalizer} = {},
) => {
const matchNormalizer = makeNormalizer({collapseWhitespace, trim, normalizer})
const allElements = Array.from(container.querySelectorAll(`[${attribute}]`))
const allNormalizedValues = new Set(
allElements.map(element =>
matchNormalizer(element.getAttribute(attribute) || ''),
),
)
const iterator = allNormalizedValues.values()
const lowerCaseSearch = searchText.toLowerCase()
let lastClosestDistance = MAX_LEVENSHTEIN_DISTANCE
let closestValues = []

for (let normalizedText; (normalizedText = iterator.next().value); ) {
if (
Math.abs(normalizedText.length - searchText.length) > lastClosestDistance
) {
// the distance cannot be closer than what we have already found
// eslint-disable-next-line no-continue
continue
}

const distance = calculateLevenshteinDistance(
normalizedText.toLowerCase(),
lowerCaseSearch,
)

if (distance > lastClosestDistance) {
// eslint-disable-next-line no-continue
continue
}

if (distance < lastClosestDistance) {
lastClosestDistance = distance
closestValues = []
}
closestValues.push(normalizedText)
}
return closestValues
}
25 changes: 23 additions & 2 deletions src/queries/test-id.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import {getCloseMatchesByAttribute} from '../close-matches'
import {checkContainerType} from '../helpers'
import {wrapAllByQueryWithSuggestion} from '../query-helpers'
import {queryAllByAttribute, getConfig, buildQueries} from './all-utils'
Expand All @@ -11,8 +12,28 @@ function queryAllByTestId(...args) {

const getMultipleError = (c, id) =>
`Found multiple elements by: [${getTestIdAttribute()}="${id}"]`
const getMissingError = (c, id) =>
`Unable to find an element by: [${getTestIdAttribute()}="${id}"]`
const getMissingError = (
c,
id,
{computeCloseMatches = false, ...options} = {},
nickmccurdy marked this conversation as resolved.
Show resolved Hide resolved
) => {
const defaultMessage = `Unable to find an element by: [${getTestIdAttribute()}="${id}"]`
if (!computeCloseMatches || typeof id !== 'string') {
return defaultMessage
}

const closeMatches = getCloseMatchesByAttribute(
getTestIdAttribute(),
c,
id,
options,
)
return closeMatches.length === 0
? defaultMessage
: `${defaultMessage}. Did you mean one of the following?\n${closeMatches.join(
'\n',
)}`
}

const queryAllByTestIdWithSuggestions = wrapAllByQueryWithSuggestion(
queryAllByTestId,
Expand Down