feat: suggest close matches using Levenshtein distance [POC]
What: Inspired by https://github.com/testing-library/dom-testing-library/issues/582
This provides a way to suggest close matches to users when the query cannot find any elements.
render(<div data-testid="cat" />)
screen.getByTestId('kat');
// output
`Unable to find an element by: [data-testid="kat"]. Did you mean one of the following?
cat`
This is a POC, looking to gather feedback to see if its worth it pursuing.
Why: Might make it easier to debug, specially when there are typos in the queries or when a certain element name has changed slightly.
How: query by attribute:
- iterate through all elements and calculate close matches
- keep only matches that are the closest to the search string, keep all that are the same distance
calculate close matches:
- initialise a dynamic programming table of size MxN where
M = element text lengthandN = search string length - use the dp table above to calculate the Levenshtein distance between the element text and the search string
Note: this was implemented only on the byTestId query for now and behind a computeClosetMatches flag
Checklist:
- [ ] Documentation added to the docs site
- [ ] Tests
- [ ] Typescript definitions updated
- [ ] Ready to be merged
This pull request is automatically built and testable in CodeSandbox.
To see build info of the built libraries, click here or the icon next to each commit SHA.
Latest deployment of this branch, based on commit 8ee261f295e2fab496d358f53b62a6afe6f46a1f:
| Sandbox | Source |
|---|---|
| react-testing-library-examples | Configuration |
Codecov Report
Merging #836 (8ee261f) into master (c6e7a83) will not change coverage. The diff coverage is
100.00%.
@@ Coverage Diff @@
## master #836 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 26 27 +1
Lines 934 965 +31
Branches 286 298 +12
=========================================
+ Hits 934 965 +31
| Impacted Files | Coverage Δ | |
|---|---|---|
| src/config.js | 100.00% <ø> (ø) |
|
| src/close-matches.js | 100.00% <100.00%> (ø) |
|
| src/queries/test-id.js | 100.00% <100.00%> (ø) |
Continue to review full report at Codecov.
Legend - Click here to learn more
Δ = absolute <relative> (impact),ø = not affected,? = missing dataPowered by Codecov. Last update c6e7a83...8ee261f. Read the comment docs.