Skip to content

Use custom testIdAttribute in getSuggestedQuery #651

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

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions src/__tests__/suggestions.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ beforeAll(() => {
configure({throwSuggestions: true})
})

afterEach(() => {
configure({testIdAttribute: 'data-testid'})
})

afterAll(() => {
configure({throwSuggestions: false})
})
Expand Down Expand Up @@ -435,6 +439,34 @@ test('getSuggestedQuery can return specified methods in addition to the best', (
expect(getSuggestedQuery(button, 'get', 'TestId')).toBeUndefined()
})

test('getSuggestedQuery works with custom testIdAttribute', () => {
configure({testIdAttribute: 'data-test'})

const {container} = render(`
<label for="username">label</label>
<input
id="username"
name="name"
placeholder="placeholder"
data-test="testid"
title="title"
alt="alt"
value="value"
type="text"
/>
<button>button</button>
`)

const input = container.querySelector('input')

expect(getSuggestedQuery(input, 'get', 'TestId')).toMatchObject({
queryName: 'TestId',
queryMethod: 'getByTestId',
queryArgs: ['testid'],
variant: 'get',
})
})

test('getSuggestedQuery does not create suggestions for script and style elements', () => {
const {container} = render(`
<script data-testid="script"></script>
Expand Down
4 changes: 2 additions & 2 deletions src/suggestions.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {computeAccessibleName} from 'dom-accessibility-api'
import {getDefaultNormalizer} from './matches'
import {getNodeText} from './get-node-text'
import {DEFAULT_IGNORE_TAGS} from './config'
import {DEFAULT_IGNORE_TAGS, getConfig} from './config'
import {getImplicitAriaRoles} from './role-helpers'

const normalize = getDefaultNormalizer()
Expand Down Expand Up @@ -120,7 +120,7 @@ export function getSuggestedQuery(element, variant = 'get', method) {
return makeSuggestion('Title', title, {variant})
}

const testId = element.getAttribute('data-testid')
const testId = element.getAttribute(getConfig().testIdAttribute)
if (canSuggest('TestId', method, testId)) {
return makeSuggestion('TestId', testId, {variant})
}
Expand Down