You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
You can extend built-in locators API by defining an object of locator factories. These methods will exist as methods on the `page` object and any created locator.
962
+
963
+
These locators can be useful if built-in locators are not enough. For example, when you use a custom framework for your UI.
964
+
965
+
The locator factory needs to return a selector string or a locator itself.
966
+
967
+
::: tip
968
+
The selector syntax is identical to Playwright locators. Please, read [their guide](https://playwright.dev/docs/other-locators) to better understand how to work with them.
969
+
:::
970
+
971
+
```ts
972
+
import { locators } from'@vitest/browser/context'
973
+
974
+
locators.extend({
975
+
getByArticleTitle(title) {
976
+
return`[data-title="${title}"]`
977
+
},
978
+
getByArticleCommentsCount(count) {
979
+
return`.comments :text("${count} comments")`
980
+
},
981
+
async previewComments() {
982
+
// you have access to the current locator via "this"
983
+
// beware that if the method was called on `page`, `this` will be `page`,
984
+
// not the locator!
985
+
if (this!==page) {
986
+
awaitthis.click()
987
+
}
988
+
// ...
989
+
}
990
+
})
991
+
992
+
// if you are using typescript, you can extend LocatorSelectors interface
993
+
// to have the autocompletion in locators.extend, page.* and locator.* methods
994
+
declaremodule'@vitest/browser/context' {
995
+
interface LocatorSelectors {
996
+
// if the custom method returns a string, it will be converted into a locator
997
+
// if it returns anything else, then it will be returned as usual
998
+
getByArticleTitle(title: string): Locator
999
+
getByArticleCommentsCount(count: number): Locator
1000
+
1001
+
// Vitest will return a promise and won't try to convert it into a locator
1002
+
previewComments(this: Locator): Promise<void>
1003
+
}
1004
+
}
1005
+
```
1006
+
1007
+
If the method is called on the global `page` object, then selector will be applied to the whole page. In the example bellow, `getByArticleTitle` will find all elements with an attribute `data-title` with the value of `title`. However, if the method is called on the locator, then it will be scoped to that locator.
0 commit comments