# Browser tests and the CI pipeline

Target: Spring '26. Sources: [Playwright](https://playwright.dev/docs/intro), [UTAM](https://utam.dev/), [`sf` CLI command reference](https://developer.salesforce.com/docs/atlas.en-us.sfdx_cli_reference.meta/sfdx_cli_reference/cli_reference_unified.htm), [Code Analyzer](https://developer.salesforce.com/docs/platform/salesforce-code-analyzer/guide/get-started.html).

## 1. Playwright against a scratch org

Get a session without a login form:

```bash
sf org display --target-org ci --json \
  | jq -r '"SF_INSTANCE_URL=" + .result.instanceUrl, "SF_ACCESS_TOKEN=" + .result.accessToken' > .env.ci
```

```js
// tests/e2e/fixtures.js
import { test as base } from '@playwright/test';

export const test = base.extend({
    orgPage: async ({ page }, use) => {
        const instance = process.env.SF_INSTANCE_URL;
        const token = process.env.SF_ACCESS_TOKEN;
        // frontdoor exchanges the access token for a UI session
        await page.goto(`${instance}/secur/frontdoor.jsp?sid=${token}`);
        await use(page);
    }
});
```

Then a journey is ordinary Playwright:

```js
test('an approver can approve an order from the record page', async ({ orgPage }) => {
    await orgPage.goto(`${process.env.SF_INSTANCE_URL}/lightning/r/Order__c/${orderId}/view`);
    await orgPage.getByRole('button', { name: 'Approve' }).click();
    await expect(orgPage.getByText('Order approved')).toBeVisible();
});
```

Notes that save hours:

- Salesforce Lightning uses **native shadow DOM**, and Playwright locators pierce shadow roots, so `getByRole`/`getByText` work. A component forced to synthetic shadow (`shadowSupportMode`) behaves differently — if a locator misses, check that first.
- Prefer role and label locators; Lightning's generated class names and ids change between releases.
- Seed data through the API, never through the UI: `sf data create record`, `sf data import tree --plan data/plan.json`, or anonymous Apex. A journey that spends two minutes creating its fixtures in forms is a journey nobody will keep green.
- **Experience Cloud guest pages** need a fresh browser context with no session at all — that is the whole point of the test. Authenticated external users get their own storage state.
- Keep the suite to a handful of journeys. Every case that can be a Jest test should be one.

## 2. UTAM vs Playwright

UTAM ships page objects for **standard** Salesforce UI, maintained by Salesforce, with Java (Selenium) and JavaScript (WebdriverIO) runtimes. That is its whole value: if a journey walks through a lot of standard pages (setup, list views, record pages, console), UTAM's page objects absorb the churn that would otherwise break selectors every release. The cost is a second toolchain and a smaller community. If most of the journey is your own components, Playwright is simpler and faster to keep green. Choosing both is a maintenance decision, not a technical one.

## 3. The whole pipeline

```yaml
# .github/workflows/ci.yml (fragment)
- run: npm ci
- run: npm run lint                       # eslint with @salesforce/eslint-config-lwc
- run: npx @salesforce-ux/slds-linter@latest lint force-app/main/default/lwc
- run: npm run test:unit -- --coverage    # sfdx-lwc-jest

- run: sf org create scratch --definition-file config/project-scratch-def.json --alias ci --duration-days 1 --wait 20
- run: sf project deploy start --target-org ci
- run: sf apex run test --target-org ci --test-level RunLocalTests --code-coverage --result-format junit --output-dir test-results --wait 30
- run: sf flow run test --target-org ci --test-level RunLocalTests --result-format junit --output-dir test-results
- run: sf code-analyzer run --workspace force-app --severity-threshold 3 --output-file code-analyzer.csv
- run: npx playwright test
- run: sf org delete scratch --target-org ci --no-prompt
  if: always()
```

- `npm run test:unit` is the `sfdx-lwc-jest` script the project scaffolding creates; run it before spending a scratch org on anything.
- `sf flow run test` needs **View All Data** on the CI user — grant it in the scratch org definition or a permission set, or the step fails on authorisation rather than on a test.
- Code Analyzer v5 covers ESLint, RetireJS and the Flow Scanner as well as PMD; `--severity-threshold 3` fails the job on moderate findings.
- Publish JUnit output from `test-results/` so failures are readable in the build, and upload the Playwright HTML report and traces on failure.
- Delete the scratch org in an `always()` step; leaked scratch orgs exhaust the daily allocation and block the whole team.

## 4. Flaky-test triage

| Symptom | Usual cause | Fix |
|---|---|---|
| Passes locally, fails in CI | Timing assumptions | `await flushPromises()` in Jest, auto-waiting locators in Playwright; never `setTimeout` |
| Fails only when the whole file runs | Leaked DOM or mock state | Reset the DOM and `jest.clearAllMocks()` in `afterEach` |
| Playwright cannot find an element that is visible | Locator based on generated markup | Role/label locators; check synthetic vs native shadow |
| Journey fails after a release upgrade | Standard UI changed | This is what UTAM page objects are for; otherwise pin the journey to your own components |
| Apex test fails only in CI | Org-dependent data or missing permission on the CI user | Build data in `@TestSetup`, never `SeeAllData`; check the permission set |
| Scratch org creation fails intermittently | Allocation exhausted or a stale definition | Delete leaked orgs, and keep the definition file minimal |
