Test the Salesforce UI for Spring '26 — LWC unit tests with `@salesforce/sfdx-lwc-jest`, mocking wired Apex with `createApexTestWireAdapter` and LDS adapters with `emit`, mocking `lightning/navigation`, `lightning/messageService`, `lightning/modal` and toasts, accessibility assertions with sa11y, Flow-screen component tests alongside `sf flow run test`, and browser journeys with Playwright or UTAM including Experience Cloud guest users.
When agents use itUse this whenever the user writes or fixes a Jest test for an LWC, sets up `jest.config.js` for a Salesforce project, asks how to mock a `@wire`, why `emit` is not a function or `toBeAccessible` is undefined, how to test an error branch, `refreshApex`, a Lightning Message Service subscriber or a Flow screen component, or how to run UI tests in CI against a scratch org. Also apply it when generating tests for LWC code the user just wrote, even if they do not say "test". Apex test classes belong to `apex-testing`.
Install
Copilot (VS Code, Visual Studio, Copilot CLI and github.com) reads skills from the repository — commit them so the whole team gets them.
npx skills add AGCO-Global/org-skills --skill salesforce-frontend-testing -a github-copilot
# or with the org installer (adds .github/skills/salesforce-frontend-testing):
npx -y github:AGCO-Global/org-skills add skill salesforce-frontend-testing
Uses the open skills CLI. Works with Claude Code, Codex, Cursor, Copilot, Gemini CLI, OpenCode, Windsurf and 60+ others — it asks which agent to install into.
Installs the salesforce-lwc-skills plugin, which bundles all Salesforce / LWC skills and keeps them updated.
/plugin marketplace add AGCO-Global/org-skills
/plugin install salesforce-lwc-skills@org-skills
# or just this skill, in this repository:
npx skills add AGCO-Global/org-skills --skill salesforce-frontend-testing -a claude-code
Use Download .zip above, then upload it under Customize → Skills → Upload skill. Team and Enterprise admins can sync this repo as a plugin marketplace instead.
Installs into .agents/skills/, which Codex reads.
npx skills add AGCO-Global/org-skills --skill salesforce-frontend-testing -a codex
Installs into Cursor's skills folder.
npx skills add AGCO-Global/org-skills --skill salesforce-frontend-testing -a cursor
Installs into Gemini CLI's skills folder.
npx skills add AGCO-Global/org-skills --skill salesforce-frontend-testing -a gemini-cli
Nothing to install. Press Download .zip above, unzip it, and drop the salesforce-frontend-testing folder into your tool's skills folder — .claude/skills/, .github/skills/, .cursor/skills/ or .agents/skills/. Step-by-step, per tool: How to use it. For any other tool with rules or custom prompts, Copy SKILL.md and paste it in — it is plain Markdown.
The npx commands need Node.js 20+ and use your normal git sign-in to GitHub, so they work while the repository is private. Without Node.js, see the No Node.js tab — a skill is a folder of Markdown, so copying it in works just as well.
Skill contents
Salesforce Frontend Testing
Targets: Salesforce Spring '26 (API 66.0), @salesforce/sfdx-lwc-jest · Verified: 2026-09 against https://developer.salesforce.com (LWC testing guide), the salesforce/sfdx-lwc-jest and trailheadapps/lwc-recipes repositories
Salesforce UI has three runtimes and therefore three test layers: Jest in Node for component behaviour, Apex tests in the org for the controllers, and a real browser against an org for what only the platform can render. Decide which layer a bug lives in before writing the test — most "we need an end-to-end test" requests are a Jest test that was never written.
1. Decide first
Question
Default
Change when
Which layer?
Jest for everything the component does with data it is given
Sharing, CRUD/FLS and limits → Apex tests (apex-testing); page composition, navigation, flows end to end → one browser journey
Mocking a @wire
LDS adapters (getRecord, getPicklistValues, …) are already test wire adapters — just emit()
Wired Apex needs createApexTestWireAdapter; imperative Apex is a plain jest.fn()
How many browser tests?
A handful of journeys that cross components
Never as a substitute for unit tests: they are slow, need an org, and fail for unrelated reasons
Browser tool
Playwright
UTAM when you drive a lot of standard Salesforce UI and want Salesforce-maintained page objects
Flow screen components
Jest for the component + sf flow run test for the flow + one browser pass
Delete-triggered or async flow paths → Apex tests only
Accessibility
await expect(element).toBeAccessible() in every component test
Add a keyboard-only pass on the main journey
Coverage
Jest coverage on lwc/, Apex coverage from apex-testing
Org bar is 90 %+ Apex (platform floor 75 %); Jest coverage is a code-health signal, not a deploy gate
2. Project setup that works
npm i -D @salesforce/sfdx-lwc-jest @sa11y/jest
// jest.config.js
const { jestConfig } = require('@salesforce/sfdx-lwc-jest/config');
const setupFilesAfterEnv = jestConfig.setupFilesAfterEnv || [];
setupFilesAfterEnv.push('<rootDir>/jest-sa11y-setup.js'); // registerSa11yMatcher() inside
module.exports = {
...jestConfig,
moduleNameMapper: {
// map only the modules you actually replace — a '^lightning/(.*)$' wildcard
// forces you to hand-write a mock for every base component
'^lightning/navigation$': '<rootDir>/force-app/test/jest-mocks/lightning/navigation',
'^lightning/messageService$': '<rootDir>/force-app/test/jest-mocks/lightning/messageService'
},
setupFilesAfterEnv,
testTimeout: 10000
};
The option is setupFilesAfterEnv — setupFilesAfterEach is not a Jest option and fails silently, leaving toBeAccessible undefined. sfdx-lwc-jest resolves its lightning/* stubs through a custom Jest resolver, so a moduleNameMapper entry replaces a stub for that one module only. Tests live in lwc/<component>/__tests__/<component>.test.js; extra mocks in force-app/test/jest-mocks/.
3. The two Apex mocks
import { createElement } from '@lwc/engine-dom';
import OrderList from 'c/orderList';
import getOrders from '@salesforce/apex/OrderController.getOrders';
import approveOrder from '@salesforce/apex/OrderController.approveOrder';
// WIRED Apex: a test wire adapter, so it has emit() and error()
jest.mock('@salesforce/apex/OrderController.getOrders', () => {
const { createApexTestWireAdapter } = require('@salesforce/sfdx-lwc-jest');
return { default: createApexTestWireAdapter(jest.fn()) };
}, { virtual: true });
// IMPERATIVE Apex: a plain mock returning a promise
jest.mock('@salesforce/apex/OrderController.approveOrder', () => ({
default: jest.fn(() => Promise.resolve())
}), { virtual: true });
const mockOrders = require('./data/getOrders.json');
const flushPromises = () => Promise.resolve();
describe('c-order-list', () => {
afterEach(() => {
while (document.body.firstChild) document.body.removeChild(document.body.firstChild);
jest.clearAllMocks();
});
it('renders the orders the wire returns', async () => {
const element = createElement('c-order-list', { is: OrderList });
document.body.appendChild(element); // append BEFORE emit — a disconnected
getOrders.emit(mockOrders); // component receives nothing
await flushPromises();
expect(element.shadowRoot.querySelectorAll('tr.order')).toHaveLength(mockOrders.length);
await expect(element).toBeAccessible();
});
it('calls approveOrder with the row id', async () => {
/* …append, emit, flush… */
element.shadowRoot.querySelector('lightning-button').click();
await flushPromises();
expect(approveOrder).toHaveBeenCalledWith({ orderId: mockOrders[0].Id });
});
});
A bare jest.fn() has noemit, so using it for a wired method fails with "emit is not a function"; and emitting before document.body.appendChild silently reaches nobody. Those two mistakes account for most broken LWC tests. The error branch is the same shape with getOrders.error(). LDS adapters such as getRecord need no jest.mock at all — import them and call emit(mockRecord) with a UI API snapshot.
4. What to test per component type
Component
Cases
Wired read
data renders · error() branch · empty result · toBeAccessible
Imperative mutation
called with the right arguments · refresh (refreshApex / notifyRecordUpdateAvailable) asserted · rejection shows the message
Form / input
validation message · CustomEvent payload · disabled state
Navigation / LMS
getNavigateCalledWith() returns the expected pageReference; publish called with channel and payload, subscriber handler invoked directly
Flow screen
FlowAttributeChangeEvent detail · validate() returns isValid: false with a message
Modal / toast
the mock was called with the right variant and message
Mock bodies for lightning/navigation, lightning/messageService, lightning/modal, toasts and lightning/refresh are in references/jest-mocks.md.
5. Browser and flow layers
Playwright journeys log in with a session from sf org display --json (or a stored storage state), cover two or three end-to-end paths, and stop. Shadow DOM is native in Salesforce UI, so Playwright's locators pierce it — page.getByRole('button', { name: 'Approve' }) works without shadow gymnastics; a component set to synthetic shadow behaves differently, so keep shadowSupportMode in mind when a locator misses. Experience Cloud guest pages need no login at all and must be tested in a fresh context. Flow logic itself is covered by sf flow run test (see salesforce-automation), not by clicking through the flow. Setup, auth and CI wiring in references/browser-and-ci.md.
6. Deliverable format
## Layers — what is covered by Jest, by Apex tests, by a browser journey
## Jest tests — complete test file(s) with both mock kinds, error branch, sa11y
## Mocks — any new file under force-app/test/jest-mocks/ and the jest.config.js entry
## Gaps — what Jest cannot prove here (sharing, limits, flow paths) and who covers it
## Run — npm run test:unit, sf apex run test, sf flow run test, the Playwright command
Element appended to the DOM beforeemit; await flushPromises() before asserting
Error branch tested with .error(); empty state tested
Imperative calls asserted with toHaveBeenCalledWith and the refresh call asserted
await expect(element).toBeAccessible() in each component's test
DOM reset and jest.clearAllMocks() in afterEach
Flow-screen components: FlowAttributeChangeEvent and validate() covered; flow itself by sf flow run test
Browser journeys limited to real cross-component paths and green in CI
Anti-patterns
jest.mock(… () => ({ default: jest.fn() })) for a wired method → createApexTestWireAdapter.
emit() before appending the element → append first; a disconnected component has no wire.
setupFilesAfterEach → setupFilesAfterEnv; moduleNameMapper: { '^lightning/(.*)$': … } → map only the modules you really replace.
modulePathIgnorePatterns: ['<rootDir>/.localdevserver'] → the retired local dev server; delete it.
Asserting a cacheable=true method "does no DML" from Apex → not enforceable at runtime in a test; catch it in review.
Snapshot tests of whole components → assert the behaviour, not the markup.
Browser tests standing in for unit tests → push the case down to Jest.
setTimeout waits in tests → await flushPromises(), or Playwright's auto-waiting locators.
Go deeper
references/jest-mocks.md — the mock files for lightning/navigation, messageService, modal, toasts and refresh, plus GraphQL wire and refreshApex assertions.
references/browser-and-ci.md — Playwright setup against a scratch org, guest-user contexts, UTAM trade-off, the full CI job with Jest, Apex, flow tests and Code Analyzer.
Sibling skills: lwc-development for the components under test, apex-testing for @AuraEnabled controller tests, salesforce-automation for Flow Tests, salesforce-devops for the pipeline, salesforce-code-review for pull requests, salesforce-org-conventions for the org's naming and mandated patterns.
---
name: salesforce-frontend-testing
description: >
Test the Salesforce UI for Spring '26 — LWC unit tests with `@salesforce/sfdx-lwc-jest`, mocking wired Apex with `createApexTestWireAdapter` and LDS adapters with `emit`, mocking `lightning/navigation`, `lightning/messageService`, `lightning/modal` and toasts, accessibility assertions with sa11y, Flow-screen component tests alongside `sf flow run test`, and browser journeys with Playwright or UTAM including Experience Cloud guest users. Use this whenever the user writes or fixes a Jest test for an LWC, sets up `jest.config.js` for a Salesforce project, asks how to mock a `@wire`, why `emit` is not a function or `toBeAccessible` is undefined, how to test an error branch, `refreshApex`, a Lightning Message Service subscriber or a Flow screen component, or how to run UI tests in CI against a scratch org. Also apply it when generating tests for LWC code the user just wrote, even if they do not say "test". Apex test classes belong to `apex-testing`.
metadata:
technology: Salesforce
type: testing
---
# Salesforce Frontend Testing
> **Targets:** Salesforce Spring '26 (API 66.0), `@salesforce/sfdx-lwc-jest` · **Verified:** 2026-09 against https://developer.salesforce.com (LWC testing guide), the `salesforce/sfdx-lwc-jest` and `trailheadapps/lwc-recipes` repositories
Salesforce UI has three runtimes and therefore three test layers: **Jest in Node** for component behaviour, **Apex tests in the org** for the controllers, and **a real browser against an org** for what only the platform can render. Decide which layer a bug lives in before writing the test — most "we need an end-to-end test" requests are a Jest test that was never written.
## 1. Decide first
| Question | Default | Change when |
|---|---|---|
| Which layer? | **Jest** for everything the component does with data it is given | Sharing, CRUD/FLS and limits → Apex tests (`apex-testing`); page composition, navigation, flows end to end → one browser journey |
| Mocking a `@wire` | LDS adapters (`getRecord`, `getPicklistValues`, …) are already test wire adapters — just `emit()` | **Wired Apex** needs `createApexTestWireAdapter`; imperative Apex is a plain `jest.fn()` |
| How many browser tests? | A handful of journeys that cross components | Never as a substitute for unit tests: they are slow, need an org, and fail for unrelated reasons |
| Browser tool | **Playwright** | UTAM when you drive a lot of **standard** Salesforce UI and want Salesforce-maintained page objects |
| Flow screen components | Jest for the component + `sf flow run test` for the flow + one browser pass | Delete-triggered or async flow paths → Apex tests only |
| Accessibility | `await expect(element).toBeAccessible()` in every component test | Add a keyboard-only pass on the main journey |
| Coverage | Jest coverage on `lwc/`, Apex coverage from `apex-testing` | Org bar is 90 %+ Apex (platform floor 75 %); Jest coverage is a code-health signal, not a deploy gate |
## 2. Project setup that works
```bash
npm i -D @salesforce/sfdx-lwc-jest @sa11y/jest
```
```js
// jest.config.js
const { jestConfig } = require('@salesforce/sfdx-lwc-jest/config');
const setupFilesAfterEnv = jestConfig.setupFilesAfterEnv || [];
setupFilesAfterEnv.push('<rootDir>/jest-sa11y-setup.js'); // registerSa11yMatcher() inside
module.exports = {
...jestConfig,
moduleNameMapper: {
// map only the modules you actually replace — a '^lightning/(.*)$' wildcard
// forces you to hand-write a mock for every base component
'^lightning/navigation$': '<rootDir>/force-app/test/jest-mocks/lightning/navigation',
'^lightning/messageService$': '<rootDir>/force-app/test/jest-mocks/lightning/messageService'
},
setupFilesAfterEnv,
testTimeout: 10000
};
```
The option is **`setupFilesAfterEnv`** — `setupFilesAfterEach` is not a Jest option and fails silently, leaving `toBeAccessible` undefined. `sfdx-lwc-jest` resolves its `lightning/*` stubs through a custom Jest **resolver**, so a `moduleNameMapper` entry replaces a stub for that one module only. Tests live in `lwc/<component>/__tests__/<component>.test.js`; extra mocks in `force-app/test/jest-mocks/`.
## 3. The two Apex mocks
```js
import { createElement } from '@lwc/engine-dom';
import OrderList from 'c/orderList';
import getOrders from '@salesforce/apex/OrderController.getOrders';
import approveOrder from '@salesforce/apex/OrderController.approveOrder';
// WIRED Apex: a test wire adapter, so it has emit() and error()
jest.mock('@salesforce/apex/OrderController.getOrders', () => {
const { createApexTestWireAdapter } = require('@salesforce/sfdx-lwc-jest');
return { default: createApexTestWireAdapter(jest.fn()) };
}, { virtual: true });
// IMPERATIVE Apex: a plain mock returning a promise
jest.mock('@salesforce/apex/OrderController.approveOrder', () => ({
default: jest.fn(() => Promise.resolve())
}), { virtual: true });
const mockOrders = require('./data/getOrders.json');
const flushPromises = () => Promise.resolve();
describe('c-order-list', () => {
afterEach(() => {
while (document.body.firstChild) document.body.removeChild(document.body.firstChild);
jest.clearAllMocks();
});
it('renders the orders the wire returns', async () => {
const element = createElement('c-order-list', { is: OrderList });
document.body.appendChild(element); // append BEFORE emit — a disconnected
getOrders.emit(mockOrders); // component receives nothing
await flushPromises();
expect(element.shadowRoot.querySelectorAll('tr.order')).toHaveLength(mockOrders.length);
await expect(element).toBeAccessible();
});
it('calls approveOrder with the row id', async () => {
/* …append, emit, flush… */
element.shadowRoot.querySelector('lightning-button').click();
await flushPromises();
expect(approveOrder).toHaveBeenCalledWith({ orderId: mockOrders[0].Id });
});
});
```
A bare `jest.fn()` has **no** `emit`, so using it for a wired method fails with "emit is not a function"; and emitting before `document.body.appendChild` silently reaches nobody. Those two mistakes account for most broken LWC tests. The error branch is the same shape with `getOrders.error()`. LDS adapters such as `getRecord` need no `jest.mock` at all — import them and call `emit(mockRecord)` with a UI API snapshot.
## 4. What to test per component type
| Component | Cases |
|---|---|
| Wired read | data renders · `error()` branch · empty result · `toBeAccessible` |
| Imperative mutation | called with the right arguments · refresh (`refreshApex` / `notifyRecordUpdateAvailable`) asserted · rejection shows the message |
| Form / input | validation message · `CustomEvent` payload · disabled state |
| Navigation / LMS | `getNavigateCalledWith()` returns the expected `pageReference`; `publish` called with channel and payload, subscriber handler invoked directly |
| Flow screen | `FlowAttributeChangeEvent` detail · `validate()` returns `isValid: false` with a message |
| Modal / toast | the mock was called with the right variant and message |
Mock bodies for `lightning/navigation`, `lightning/messageService`, `lightning/modal`, toasts and `lightning/refresh` are in `references/jest-mocks.md`.
## 5. Browser and flow layers
Playwright journeys log in with a session from `sf org display --json` (or a stored storage state), cover two or three end-to-end paths, and stop. Shadow DOM is native in Salesforce UI, so Playwright's locators pierce it — `page.getByRole('button', { name: 'Approve' })` works without shadow gymnastics; a component set to synthetic shadow behaves differently, so keep `shadowSupportMode` in mind when a locator misses. Experience Cloud guest pages need no login at all and must be tested in a fresh context. Flow logic itself is covered by `sf flow run test` (see `salesforce-automation`), not by clicking through the flow. Setup, auth and CI wiring in `references/browser-and-ci.md`.
## 6. Deliverable format
```
## Layers — what is covered by Jest, by Apex tests, by a browser journey
## Jest tests — complete test file(s) with both mock kinds, error branch, sa11y
## Mocks — any new file under force-app/test/jest-mocks/ and the jest.config.js entry
## Gaps — what Jest cannot prove here (sharing, limits, flow paths) and who covers it
## Run — npm run test:unit, sf apex run test, sf flow run test, the Playwright command
```
## Checklist
- [ ] `setupFilesAfterEnv` (never `setupFilesAfterEach`); sa11y matcher registered
- [ ] `moduleNameMapper` maps specific modules, not a `lightning/*` wildcard
- [ ] Wired Apex uses `createApexTestWireAdapter`; imperative Apex uses `jest.fn()`
- [ ] Element appended to the DOM **before** `emit`; `await flushPromises()` before asserting
- [ ] Error branch tested with `.error()`; empty state tested
- [ ] Imperative calls asserted with `toHaveBeenCalledWith` and the refresh call asserted
- [ ] `await expect(element).toBeAccessible()` in each component's test
- [ ] DOM reset and `jest.clearAllMocks()` in `afterEach`
- [ ] Flow-screen components: `FlowAttributeChangeEvent` and `validate()` covered; flow itself by `sf flow run test`
- [ ] Browser journeys limited to real cross-component paths and green in CI
## Anti-patterns
- **`jest.mock(… () => ({ default: jest.fn() }))` for a wired method** → `createApexTestWireAdapter`.
- **`emit()` before appending the element** → append first; a disconnected component has no wire.
- **`setupFilesAfterEach`** → `setupFilesAfterEnv`; **`moduleNameMapper: { '^lightning/(.*)$': … }`** → map only the modules you really replace.
- **`modulePathIgnorePatterns: ['<rootDir>/.localdevserver']`** → the retired local dev server; delete it.
- **Asserting a `cacheable=true` method "does no DML" from Apex** → not enforceable at runtime in a test; catch it in review.
- **Snapshot tests of whole components** → assert the behaviour, not the markup.
- **Browser tests standing in for unit tests** → push the case down to Jest.
- **`setTimeout` waits in tests** → `await flushPromises()`, or Playwright's auto-waiting locators.
## Go deeper
- `references/jest-mocks.md` — the mock files for `lightning/navigation`, `messageService`, `modal`, toasts and `refresh`, plus GraphQL wire and `refreshApex` assertions.
- `references/browser-and-ci.md` — Playwright setup against a scratch org, guest-user contexts, UTAM trade-off, the full CI job with Jest, Apex, flow tests and Code Analyzer.
- Sibling skills: `lwc-development` for the components under test, `apex-testing` for `@AuraEnabled` controller tests, `salesforce-automation` for Flow Tests, `salesforce-devops` for the pipeline, `salesforce-code-review` for pull requests, `salesforce-org-conventions` for the org's naming and mandated patterns.