-
Notifications
You must be signed in to change notification settings - Fork 42
Add rule to suggest using built-in locators (prefer-native-locators
)
#308
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
mskelton
merged 26 commits into
playwright-community:main
from
camchenry:rule/prefer-native-locators
Sep 6, 2024
Merged
Changes from 13 commits
Commits
Show all changes
26 commits
Select commit
Hold shift + click to select a range
56eea9c
Add label text query
camchenry 3cce6b9
Add role query
camchenry f30eeaa
Add placeholder query
camchenry d19ef20
Add alt text query
camchenry 01e14d3
Add test ID query
camchenry 98795fa
Add title query
camchenry dacf2c2
Simplify text matching and replacement
camchenry 558f03d
Put new text in its own variable
camchenry 19c486e
Add support for custom test ID attribute
camchenry 6a5d92a
Add more tests
camchenry 8e80331
Add docs
camchenry 7524dc6
Add prefer-native-locators to README
camchenry 7eaf787
Export prefer-native-locators rule
camchenry 61fbebb
Move patterns to array
camchenry c3b834d
Drop periods from messages
camchenry a93d0eb
Remove non-page locator method check
camchenry 4c7ecaf
Add tests for empty string + no args
camchenry 12798a1
Use AST.Range instead of tuple
camchenry a77f3a3
Add more tests
camchenry 62f9a89
Allow replacing for selectors without quotes
camchenry a65e8e4
Add docs on testIdAttribute
camchenry 7ee29d8
Undo line-break
camchenry 0626abe
Use same RegExp for each attribute
camchenry 0be9b19
Move range into fixer
camchenry 06ec0f6
Remove unnecessary identifier
camchenry ccd2fc5
Add more test cases
camchenry File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
# Suggest using native Playwright locators (`prefer-native-locators`) | ||
|
||
Playwright has built-in locators for common query selectors such as finding | ||
elements by placeholder text, ARIA role, accessible name, and more. This rule | ||
suggests using these native locators instead of using `page.locator()` with an | ||
equivalent selector. | ||
|
||
In some cases this can be more robust too, such as finding elements by ARIA role | ||
or accessible name, because some elements have implicit roles, and there are | ||
multiple ways to specify accessible names. | ||
|
||
## Rule details | ||
|
||
Examples of **incorrect** code for this rule: | ||
|
||
```javascript | ||
page.locator('[aria-label="View more"]') | ||
page.locator('[role="button"]') | ||
page.locator('[placeholder="Enter some text..."]') | ||
page.locator('[alt="Playwright logo"]') | ||
page.locator('[title="Additional context"]') | ||
page.locator('[data-testid="password-input"]') | ||
``` | ||
|
||
Examples of **correct** code for this rule: | ||
|
||
```javascript | ||
page.getByLabel('View more') | ||
page.getByRole('Button') | ||
page.getByPlaceholder('Enter some text...') | ||
page.getByAltText('Playwright logo') | ||
page.getByTestId('password-input') | ||
page.getByTitle('Additional context') | ||
``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,98 @@ | ||
import { runRuleTester } from '../utils/rule-tester' | ||
import rule from './prefer-native-locators' | ||
|
||
runRuleTester('prefer-native-locators', rule, { | ||
invalid: [ | ||
{ | ||
code: `page.locator('[aria-label="View more"]')`, | ||
errors: [{ column: 1, line: 1, messageId: 'unexpectedLabelQuery' }], | ||
output: 'page.getByLabel("View more")', | ||
}, | ||
{ | ||
code: `page.locator('[role="button"]')`, | ||
errors: [{ column: 1, line: 1, messageId: 'unexpectedRoleQuery' }], | ||
output: 'page.getByRole("button")', | ||
}, | ||
{ | ||
code: `page.locator('[placeholder="Enter some text..."]')`, | ||
errors: [{ column: 1, line: 1, messageId: 'unexpectedPlaceholderQuery' }], | ||
output: 'page.getByPlaceholder("Enter some text...")', | ||
}, | ||
{ | ||
code: `page.locator('[alt="Playwright logo"]')`, | ||
errors: [{ column: 1, line: 1, messageId: 'unexpectedAltTextQuery' }], | ||
output: 'page.getByAltText("Playwright logo")', | ||
}, | ||
{ | ||
code: `page.locator('[title="Additional context"]')`, | ||
errors: [{ column: 1, line: 1, messageId: 'unexpectedTitleQuery' }], | ||
output: 'page.getByTitle("Additional context")', | ||
}, | ||
{ | ||
code: `page.locator('[data-testid="password-input"]')`, | ||
errors: [{ column: 1, line: 1, messageId: 'unexpectedTestIdQuery' }], | ||
output: 'page.getByTestId("password-input")', | ||
}, | ||
{ | ||
code: `page.locator('[data-custom-testid="password-input"]')`, | ||
errors: [{ column: 1, line: 1, messageId: 'unexpectedTestIdQuery' }], | ||
options: [{ testIdAttribute: 'data-custom-testid' }], | ||
output: 'page.getByTestId("password-input")', | ||
}, | ||
// Works when locators are chained | ||
{ | ||
code: `this.page.locator('[role="heading"]').first()`, | ||
errors: [{ column: 1, line: 1, messageId: 'unexpectedRoleQuery' }], | ||
output: 'this.page.getByRole("heading").first()', | ||
}, | ||
// Works when used inside an assertion | ||
{ | ||
code: `await expect(page.locator('[role="alert"]')).toBeVisible()`, | ||
errors: [{ column: 14, line: 1, messageId: 'unexpectedRoleQuery' }], | ||
output: 'await expect(page.getByRole("alert")).toBeVisible()', | ||
}, | ||
{ | ||
code: `await expect(page.locator('[data-testid="top"]')).toContainText(firstRule)`, | ||
errors: [{ column: 14, line: 1, messageId: 'unexpectedTestIdQuery' }], | ||
output: 'await expect(page.getByTestId("top")).toContainText(firstRule)', | ||
}, | ||
// Works when used as part of an action | ||
{ | ||
code: `await page.locator('[placeholder="New password"]').click()`, | ||
errors: [{ column: 7, line: 1, messageId: 'unexpectedPlaceholderQuery' }], | ||
output: 'await page.getByPlaceholder("New password").click()', | ||
}, | ||
// Works when it is not page.locator | ||
{ | ||
code: `this.locator('[aria-label="View more"]')`, | ||
errors: [{ column: 1, line: 1, messageId: 'unexpectedLabelQuery' }], | ||
output: 'this.getByLabel("View more")', | ||
}, | ||
], | ||
valid: [ | ||
{ code: 'page.getByLabel("View more")' }, | ||
camchenry marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ code: 'page.getByRole("button")' }, | ||
{ code: 'page.getByPlaceholder("Enter some text...")' }, | ||
{ code: 'page.getByAltText("Playwright logo")' }, | ||
{ code: 'page.getByTestId("password-input")' }, | ||
{ code: 'page.getByTitle("Additional context")' }, | ||
{ | ||
code: `page.locator('[complex-query] > [aria-label="View more"]')`, | ||
}, | ||
{ | ||
code: `page.locator('[complex-query] > [role="button"]')`, | ||
}, | ||
{ | ||
code: `page.locator('[complex-query] > [placeholder="Enter some text..."]')`, | ||
}, | ||
{ | ||
code: `page.locator('[complex-query] > [alt="Playwright logo"]')`, | ||
}, | ||
{ | ||
code: `page.locator('[complex-query] > [data-testid="password-input"]')`, | ||
}, | ||
{ | ||
code: `page.locator('[complex-query] > [title="Additional context"]')`, | ||
}, | ||
], | ||
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,139 @@ | ||
import { getStringValue, isPageMethod } from '../utils/ast' | ||
import { createRule } from '../utils/createRule' | ||
|
||
export default createRule({ | ||
create(context) { | ||
return { | ||
CallExpression(node) { | ||
const { testIdAttribute } = { | ||
testIdAttribute: 'data-testid', | ||
...((context.options?.[0] as Record<string, unknown>) ?? {}), | ||
} | ||
|
||
if (node.callee.type !== 'MemberExpression') return | ||
const method = getStringValue(node.callee.property) | ||
const query = getStringValue(node.arguments[0]) | ||
camchenry marked this conversation as resolved.
Show resolved
Hide resolved
|
||
const isLocator = isPageMethod(node, 'locator') || method === 'locator' | ||
camchenry marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if (!isLocator) return | ||
|
||
// If it's something like `page.locator`, just replace the `.locator` part | ||
const start = | ||
node.callee.type === 'MemberExpression' | ||
? node.callee.property.range![0] | ||
: node.range![0] | ||
const end = node.range![1] | ||
const rangeToReplace: [number, number] = [start, end] | ||
camchenry marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
const ariaLabelPattern = /^\[aria-label=['"](.+?)['"]\]$/ | ||
camchenry marked this conversation as resolved.
Show resolved
Hide resolved
|
||
const labelMatch = query.match(ariaLabelPattern) | ||
if (labelMatch) { | ||
context.report({ | ||
fix(fixer) { | ||
const newText = `getByLabel("${labelMatch[1]}")` | ||
return fixer.replaceTextRange(rangeToReplace, newText) | ||
}, | ||
messageId: 'unexpectedLabelQuery', | ||
node, | ||
}) | ||
} | ||
|
||
const rolePattern = /^\[role=['"](.+?)['"]\]$/ | ||
const roleMatch = query.match(rolePattern) | ||
if (roleMatch) { | ||
context.report({ | ||
fix(fixer) { | ||
const newText = `getByRole("${roleMatch[1]}")` | ||
return fixer.replaceTextRange(rangeToReplace, newText) | ||
}, | ||
messageId: 'unexpectedRoleQuery', | ||
node, | ||
}) | ||
} | ||
|
||
const placeholderPattern = /^\[placeholder=['"](.+?)['"]\]$/ | ||
const placeholderMatch = query.match(placeholderPattern) | ||
if (placeholderMatch) { | ||
context.report({ | ||
fix(fixer) { | ||
const newText = `getByPlaceholder("${placeholderMatch[1]}")` | ||
return fixer.replaceTextRange(rangeToReplace, newText) | ||
}, | ||
messageId: 'unexpectedPlaceholderQuery', | ||
node, | ||
}) | ||
} | ||
|
||
const altTextPattern = /^\[alt=['"](.+?)['"]\]$/ | ||
const altTextMatch = query.match(altTextPattern) | ||
if (altTextMatch) { | ||
context.report({ | ||
fix(fixer) { | ||
const newText = `getByAltText("${altTextMatch[1]}")` | ||
return fixer.replaceTextRange(rangeToReplace, newText) | ||
}, | ||
messageId: 'unexpectedAltTextQuery', | ||
node, | ||
}) | ||
} | ||
|
||
const titlePattern = /^\[title=['"](.+?)['"]\]$/ | ||
const titleMatch = query.match(titlePattern) | ||
if (titleMatch) { | ||
context.report({ | ||
fix(fixer) { | ||
const newText = `getByTitle("${titleMatch[1]}")` | ||
return fixer.replaceTextRange(rangeToReplace, newText) | ||
}, | ||
messageId: 'unexpectedTitleQuery', | ||
node, | ||
}) | ||
} | ||
|
||
const testIdPattern = new RegExp( | ||
`^\\[${testIdAttribute}=['"](.+?)['"]\\]`, | ||
) | ||
const testIdMatch = query.match(testIdPattern) | ||
if (testIdMatch) { | ||
context.report({ | ||
fix(fixer) { | ||
const newText = `getByTestId("${testIdMatch[1]}")` | ||
return fixer.replaceTextRange(rangeToReplace, newText) | ||
}, | ||
messageId: 'unexpectedTestIdQuery', | ||
node, | ||
}) | ||
} | ||
}, | ||
} | ||
}, | ||
meta: { | ||
docs: { | ||
category: 'Best Practices', | ||
description: 'Prefer native locator functions', | ||
recommended: false, | ||
url: 'https://github.com/playwright-community/eslint-plugin-playwright/tree/main/docs/rules/prefer-native-locators.md', | ||
}, | ||
fixable: 'code', | ||
messages: { | ||
unexpectedAltTextQuery: 'Use .getByAltText() instead', | ||
unexpectedLabelQuery: 'Use .getByLabel() instead', | ||
unexpectedPlaceholderQuery: 'Use .getByPlaceholder() instead', | ||
unexpectedRoleQuery: 'Use .getByRole() instead', | ||
unexpectedTestIdQuery: 'Use .getByTestId() instead', | ||
unexpectedTitleQuery: 'Use .getByTitle() instead', | ||
camchenry marked this conversation as resolved.
Show resolved
Hide resolved
|
||
}, | ||
schema: [ | ||
{ | ||
additionalProperties: false, | ||
properties: { | ||
testIdAttribute: { | ||
default: 'data-testid', | ||
type: 'string', | ||
}, | ||
}, | ||
type: 'object', | ||
}, | ||
], | ||
type: 'suggestion', | ||
}, | ||
}) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.