Skip to content

Commit 5dac03a

Browse files
committed
implement closest matches suggestions on testId query
1 parent 371923b commit 5dac03a

File tree

2 files changed

+62
-2
lines changed

2 files changed

+62
-2
lines changed

src/__tests__/element-queries.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1273,3 +1273,42 @@ it(`should get element by it's label when there are elements with same text`, ()
12731273
`)
12741274
expect(getByLabelText('test 1')).toBeInTheDocument()
12751275
})
1276+
1277+
test('returns closest match when computeCloseMatches = true', () => {
1278+
const {getByTestId} = render(`
1279+
<div>
1280+
<div data-testid="cat-dog"></div>
1281+
<div data-testid="meerkat"></div>
1282+
<div data-testid="tamandua"></div>
1283+
</div>`)
1284+
1285+
expect(() => getByTestId('meercat', {computeCloseMatches: true}))
1286+
.toThrowErrorMatchingInlineSnapshot(`
1287+
"Unable to find an element by: [data-testid="meercat"]. Did you mean one of the following?
1288+
meerkat
1289+
1290+
<div>
1291+
1292+
1293+
<div>
1294+
1295+
1296+
<div
1297+
data-testid="cat-dog"
1298+
/>
1299+
1300+
1301+
<div
1302+
data-testid="meerkat"
1303+
/>
1304+
1305+
1306+
<div
1307+
data-testid="tamandua"
1308+
/>
1309+
1310+
1311+
</div>
1312+
</div>"
1313+
`)
1314+
})

src/queries/test-id.js

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import {getCloseMatchesByAttribute} from '../close-matches'
12
import {checkContainerType} from '../helpers'
23
import {wrapAllByQueryWithSuggestion} from '../query-helpers'
34
import {queryAllByAttribute, getConfig, buildQueries} from './all-utils'
@@ -11,8 +12,28 @@ function queryAllByTestId(...args) {
1112

1213
const getMultipleError = (c, id) =>
1314
`Found multiple elements by: [${getTestIdAttribute()}="${id}"]`
14-
const getMissingError = (c, id) =>
15-
`Unable to find an element by: [${getTestIdAttribute()}="${id}"]`
15+
const getMissingError = (
16+
c,
17+
id,
18+
{computeCloseMatches = false, ...options} = {},
19+
) => {
20+
const defaultMessage = `Unable to find an element by: [${getTestIdAttribute()}="${id}"]`
21+
if (!computeCloseMatches || typeof id !== 'string') {
22+
return defaultMessage
23+
}
24+
25+
const closeMatches = getCloseMatchesByAttribute(
26+
getTestIdAttribute(),
27+
c,
28+
id,
29+
options,
30+
)
31+
return closeMatches.length === 0
32+
? defaultMessage
33+
: `${defaultMessage}. Did you mean one of the following?\n${closeMatches.join(
34+
'\n',
35+
)}`
36+
}
1637

1738
const queryAllByTestIdWithSuggestions = wrapAllByQueryWithSuggestion(
1839
queryAllByTestId,

0 commit comments

Comments
 (0)