|  | 
| 1 | 1 | # Selenium Testing Library | 
| 2 | 2 | 
 | 
| 3 | 3 | A set of Selenium locators inspired by the [Testing Library](http://testing-library.com/). | 
|  | 4 | +A few examples: | 
|  | 5 | +```kotlin | 
|  | 6 | +driver.findElements(ByText("first name", exact = false, selector="span")) | 
|  | 7 | +driver.findElements(ByPlaceholderText("first name")) | 
|  | 8 | +driver.findElements(ByPlaceholderText("first name", exact = false)) | 
|  | 9 | +driver.findElements(ByTitle("first name")) | 
|  | 10 | +driver.findElements(ByDisplayValue("first name")) | 
|  | 11 | +driver.findElements(ByTestId("test-id")) | 
|  | 12 | +``` | 
|  | 13 | +There are unit tests that [illustrate](https://medium.com/codex/towards-self-documenting-code-371364bdccbb)  | 
|  | 14 | +all the usages (this was done with TDD/test-first). | 
|  | 15 | + | 
|  | 16 | +## Why? | 
|  | 17 | +I'm a fan of the [Testing Library](http://testing-library.com/). | 
|  | 18 | +It has ports for many frameworks but Selenium was missing. | 
|  | 19 | +When I use Selenium, I don't want to depend on ids, classes, and similar. | 
|  | 20 | +Happily, Selenium is easily expandable by adding new Locators (just inherit from `By`). | 
|  | 21 | + | 
|  | 22 | +## How? | 
|  | 23 | +My approach was to create a Kotlin [adapter](https://en.wikipedia.org/wiki/Adapter_pattern): | 
|  | 24 | +a set of custom Selenium that is just wrappers around the Testing Library JavaScript functions. | 
|  | 25 | + | 
|  | 26 | +How do I have the Testing Library in Selenium? By dynamically injecting it through JavaScript. | 
|  | 27 | +The injected JavaScript was copied from the [Testing Playground Chrome extension](https://chrome.google.com/webstore/detail/testing-playground/hejbmebodbijjdhflfknehhcgaklhano). | 
|  | 28 | +(There are some CDKs that serve the Testing Library,  | 
|  | 29 | +but I needed the self-contained single-file browser-ready version.) | 
|  | 30 | + | 
|  | 31 | +My first approach was to use Selenium locators (e.g. `xpath`, `cssSelector`) to port the Testing Library behavior. | 
|  | 32 | +It turned out this was a limited approach because: | 
|  | 33 | +- Selenium locators are limited due to [WebdriverIO](https://webdriver.io/) limitations | 
|  | 34 | +- I'd have to port everything, which is a lot of work | 
|  | 35 | +- I'd likely introduce bugs | 
|  | 36 | +- I wouldn't get library updates easily | 
|  | 37 | +(check git history to view the old approach) | 
|  | 38 | +With the new approach, I learned a lot about Selenium, the Testing Library, and publishing a library. | 
0 commit comments