Files
e2e/docs/migrate/selenium.mdx
T

134 lines
7.5 KiB
Plaintext

---
title: From Selenium
description: Rewrite Selenium flows in TypeScript with locators, retrying assertions, and agent goals.
---
import { SetupPrompt } from '../snippets/setup-prompt-card.jsx';
export const migrationPrompt = `Migrate this project's Selenium tests to e2e, one flow at a time. Docs: \`https://e2e.tester.army/docs/migrate/selenium.md\`
1. Read the migration guide above. It maps Selenium config and WebDriver calls to e2e.
2. e2e tests are TypeScript. If the Selenium suite is Java, Python, or another language, ask me where the new test project should live, for example an \`e2e/\` folder with its own \`package.json\`.
3. If that project has no e2e config (\`e2e.config.ts\` or \`e2e.config.mts\`), run \`npx e2e init --yes\` (or the pnpm or bun equivalent) there. It writes a config and an example test, and installs nothing yet.
4. Read the e2e skill (\`npx e2e guide\` prints it, \`npx e2e guide <topic>\` prints a topic) and follow it for every step below.
5. If you ran init, ask me which model to use for agent steps: a ChatGPT, GitHub Copilot, OpenCode Console, or SuperGrok subscription, an API key, or a local model. Configure it with its provider package. If it needs a sign-in, give me the \`npx e2e login\` command and wait until I confirm.
6. Set the target's \`app\` to the URL every \`driver.get\` used, and the command that starts the app if the suite starts it. Move passwords and tokens into \`credentials\` or \`secrets\`.
7. Install dependencies.
8. List the page objects and the flows that use them, and ask me which to move first. Suggest one page object and its flows.
9. Rewrite those flows as \`.e2e.ts\` files under \`tests/\` (e2e runs \`tests/**/*.e2e.ts\` by default). Prefer role, label, and test id queries on \`screen\` over \`By.id\`, CSS, and XPath. Replace explicit waits, implicit waits, and \`Thread.sleep\` with locator assertions, which retry. \`findElement\` takes the first match and e2e fails on several, so narrow those queries. Turn the page object's setup code into a fixture.
10. Keep navigation and the final assertions deterministic, with \`app.open()\` and locator assertions. Where a run of scripted interactions breaks often, propose an \`agent.act\` goal for it instead.
11. Run the new files with \`npx e2e run <file>\` and fix them until they pass. Keep the Selenium tests until I confirm they can go.
12. Summarize which flows moved, which stayed in Selenium, and why.`;
<SetupPrompt>
<Prompt description={migrationPrompt} children={migrationPrompt} actions={["copy", "cursor"]} />
</SetupPrompt>
e2e tests use TypeScript, locators based on roles and labels, and assertions
that retry until they pass or time out. A Java or Python suite needs to be
rewritten. Run both suites while you move one flow at a time.
Follow the [quickstart](/quickstart) to install e2e. A model is needed only for
agent calls; the locator-based example below works without one.
## Config
| Selenium | e2e |
| --- | --- |
| The URL in every `driver.get` | `app: { url }` on the target, then relative paths |
| Starting the app in a script | `app: { url, command }`, see [Starting your app](/starting-your-app) |
| One driver per browser | One target per browser, `web({ browser: 'firefox' })` |
| Selenium Grid | `workers` for parallelism; `connect` attaches to a remote Chromium over CDP, and a [browser provider](/browser#hosted-browsers) such as [Kernel](/integrations/kernel) leases hosted browsers |
| `manage().window().setSize` | `web({ viewport })` |
| Implicit waits | `actionTimeout` and `assertionTimeout` set action and assertion deadlines |
| A page object for sign-in | `test.setup` and `{ session }`, see [Signing in](/authentication) |
## A test, before and after
```java title="Selenium"
driver.get("http://localhost:3000/login");
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(visibilityOfElementLocated(By.id("username"))).sendKeys("admin@example.test");
driver.findElement(By.id("password")).sendKeys(System.getenv("ADMIN_PASSWORD"));
driver.findElement(By.xpath("//button[contains(., 'Sign in')]")).click();
wait.until(urlContains("/dashboard"));
assertEquals("Welcome back, admin!",
driver.findElement(By.cssSelector(".greeting")).getText());
```
```ts title="e2e"
import { test } from '@e2e-dev/web';
import { expect, credentials } from 'e2e';
test('signs in', async ({ app, screen, browser }) => {
const admin = credentials.user('admin');
await app.open('/login');
await screen.getByLabel('Username').fill(admin.username);
await screen.getByLabel('Password').fill(admin.password);
await screen.getByRole('button', 'Sign in').tap();
await expect(browser).toHaveURL('/dashboard');
await expect(screen.getByRole('status')).toHaveText('Welcome back, admin!');
});
```
The locator actions wait for their targets and the assertions retry. The
password comes from [configured credentials](/authentication). You can also
use `agent.act` to perform sign-in from a goal.
## API map
| Selenium | e2e |
| --- | --- |
| `driver.get(url)` | `app.open(path)` |
| `driver.navigate().back()`, `.refresh()` | `app.back()`, `browser.reload()` |
| `By.id('x')` | `browser.locator('#x')`; or `web({ testIdAttribute: 'id' })` and `screen.getByTestId('x')` |
| `By.name('x')` | `browser.locator('[name="x"]')`, not portable; prefer a role or label |
| `By.linkText`, `By.partialLinkText` | `screen.getByRole('link', { name })`, `name: /part/` |
| `By.cssSelector`, `By.xpath` | `browser.locator('css or xpath')`, not portable |
| `findElements(...).size()` | `await locator.count()` |
| `findElements(...).get(n)` | `locator.nth(n)` |
| `.click()` | `.tap()` |
| `.sendKeys('text')` | `.fill('text')` replaces the content |
| `.sendKeys(Keys.ENTER)` | `.press('Enter')` |
| `.clear()` | `.clear()` |
| `new Select(el).selectByVisibleText` | `.selectOption({ label })` |
| `.getText()`, `.getAttribute()`, `.isDisplayed()` | `.textContent()`, `.getAttribute()`, `.isVisible()`, no retry |
| `wait.until(visibilityOf(...))` | `await expect(locator).toBeVisible()` |
| `wait.until(textToBe(...))` | `await expect(locator).toHaveText(...)` |
| `wait.until(urlContains(...))` | `await expect(browser).toHaveURL(/.../)` |
| `Actions.moveToElement` | `.hover()` |
| `Actions.dragAndDrop` | `.dragTo(target)` |
| `Actions.keyDown(CONTROL).sendKeys('a')` | `.press('ControlOrMeta+a')` |
| `switchTo().frame()` | `browser.frameLocator('#frame')` |
| `switchTo().alert().accept()` | `browser.onDialog('accept')` before the action |
| `switchTo().window()` | No equivalent. Popups are unsupported |
| `executeScript` | `browser.evaluate` |
| `manage().addCookie` | `browser.setCookies` |
| `getScreenshotAs` | `app.screenshot('label')`, redacted |
| `Thread.sleep` | Use a locator assertion for the condition you need |
| Page objects | A fixture from `test.extend`, or a goal for `agent.act` |
Where the behavior differs from WebDriver's:
- `findElement` returns the first match; e2e fails with `LOCATOR_AMBIGUOUS`.
Narrow with `.filter()`, `.first()`, or `.nth()`, see
[screen](/reference/screen).
- `textContent()` reads once and does not retry. Assert with `toHaveText()`,
which polls until the deadline.
## What to migrate first
Start with one page object and the flows that use it; its setup code can
become a fixture.
<CardGroup cols={2}>
<Card title="Goals" icon="pen-to-square" href="/goals">
Write test steps as goals instead of scripted selectors.
</Card>
<Card title="screen reference" icon="crosshairs" href="/reference/screen">
Every query, refinement, action, and read.
</Card>
</CardGroup>