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 all 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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
"aria-query": "^4.2.2",
"chalk": "^4.1.0",
"dom-accessibility-api": "^0.5.4",
"leven": "^3.1.0",
"lz-string": "^1.4.4",
"pretty-format": "^26.6.2"
},
Expand Down
49 changes: 49 additions & 0 deletions src/__tests__/close-matches.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import {getCloseMatchesByAttribute} from '../close-matches'
import {render} from './helpers/test-utils'

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>
<div data-testid></div>
<div></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'])
})
})
77 changes: 77 additions & 0 deletions src/__tests__/element-queries.js
Original file line number Diff line number Diff line change
Expand Up @@ -1273,3 +1273,80 @@ 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>"
`)
})

test('returns default error message when computeCloseMatches = true but cant find any good suggestions', () => {
const {getByTestId} = render(`
<div>
<div data-testid="cat-dog"></div>
<div data-testid="meerkat"></div>
<div data-testid="tamandua"></div>
</div>`)

expect(() => getByTestId('white-shark', {computeCloseMatches: true}))
.toThrowErrorMatchingInlineSnapshot(`
"Unable to find an element by: [data-testid="white-shark"]

<div>


<div>


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


<div
data-testid="meerkat"
/>


<div
data-testid="tamandua"
/>


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

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
}
1 change: 1 addition & 0 deletions src/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ let config = {
},
_disableExpensiveErrorDiagnostics: false,
computedStyleSupportsPseudoElements: false,
computeCloseMatches: false,
}

export const DEFAULT_IGNORE_TAGS = 'script, style'
Expand Down
21 changes: 19 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,24 @@ 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 = getConfig().computeCloseMatches, ...options} = {},
) => {
const defaultMessage = `Unable to find an element by: [${getTestIdAttribute()}="${id}"]`

const closeMatches =
!computeCloseMatches || typeof id !== 'string'
? []
: getCloseMatchesByAttribute(getTestIdAttribute(), c, id, options)
Comment on lines +22 to +25
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm concerned about this increasing the performance issues we already have with find* queries which are expected to fail at least once. Any chance we could lazily calculate this value so it's only run when the error is actually displayed? I don't know whether this is possible.

But perhaps my concern is unwarranted? Maybe this is faster than I think?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm concerned about this increasing the performance issues we already have with find* queries which are expected to fail at least once.

Good point. I tested a few times on my local running getByTestId('search', {computeCloseMatches: true}) vs getByTestId('search', {computeCloseMatches: false}).

Not a reliable benchmark, but when false it finished consistently at around 20ms. When true finished at around 35ms. It increases with the number of elements found, but not by much. Might become slightly quicker with the recommended lib.

Any chance we could lazily calculate this value so it's only run when the error is actually displayed?

An alternative would be to throw functions for find* queries. And then check if typeof lastError === 'function' when waitFor times out.

That might mean decoupling find* and get* queries a bit or perhaps make get queries depend on find queries instead of the other way around.

i.e: a get* query could be a find* query with {timeout: 0, interval: Infinity} ? (not sure if that would work)

Since that seems a bit involved, we could start with a config computeCloseMatches that defaults to false and give that some testing?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm ok with giving it a trial run and seeing what real-world experience with it will be like, so defaulting to disabled makes sense to me. Let's try it out using leven.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kentcdodds do you think we should start with the testId query or add this feature to all 10 queries? Wondering if i can break down the work somehow...

Re. the performance concern. Maybe if we realise there is a huge performance impact we can skip the computation of close matches on find* queries(similar to what was done for the role query here: #590

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure. What does everyone else think?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO if the default is false, we can give it a try in more queries, though, this seems to me like a configuration that shouldn't be set to true by default at all, especially since it has a performance impact. I see this as something that will not be helpful in CI for example and will only take more time so if the developer wants to opt in they will have an option to do that.
Putting aside what I wrote above, I really like this PR and do think it can have a valuable impact so thanks for this :)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you please try a benchmark again using the new leven implementation?


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

const queryAllByTestIdWithSuggestions = wrapAllByQueryWithSuggestion(
queryAllByTestId,
Expand Down