lwc-testing

Use when setting up or reviewing Lightning Web Component unit tests with Jest, including `@salesforce/sfdx-lwc-jest`, wire adapter mocks, imperative Apex mocks, async rerender handling, and accessibility smoke checks. Triggers: 'how do I test @wire in LWC', 'Jest test is flaky', 'mock Apex in LWC test', 'flushPromises pattern'. NOT for Apex unit tests, browser end-to-end automation, or performance testing.

Best use case

lwc-testing is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Use when setting up or reviewing Lightning Web Component unit tests with Jest, including `@salesforce/sfdx-lwc-jest`, wire adapter mocks, imperative Apex mocks, async rerender handling, and accessibility smoke checks. Triggers: 'how do I test @wire in LWC', 'Jest test is flaky', 'mock Apex in LWC test', 'flushPromises pattern'. NOT for Apex unit tests, browser end-to-end automation, or performance testing.

Teams using lwc-testing should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/lwc-testing/SKILL.md --create-dirs "https://raw.githubusercontent.com/PranavNagrecha/AwesomeSalesforceSkills/main/skills/lwc/lwc-testing/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/lwc-testing/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How lwc-testing Compares

Feature / Agentlwc-testingStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Use when setting up or reviewing Lightning Web Component unit tests with Jest, including `@salesforce/sfdx-lwc-jest`, wire adapter mocks, imperative Apex mocks, async rerender handling, and accessibility smoke checks. Triggers: 'how do I test @wire in LWC', 'Jest test is flaky', 'mock Apex in LWC test', 'flushPromises pattern'. NOT for Apex unit tests, browser end-to-end automation, or performance testing.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

Use this skill when the component works in the browser but the test suite does not prove it reliably. LWC testing is mostly about isolating behavior, mocking the right Salesforce boundaries, and waiting for rerenders intentionally instead of guessing at timing.

---

## Before Starting

Gather this context before working on anything in this domain:

- What behavior matters most: initial render, user interaction, wired data, imperative save, error state, or navigation?
- Which platform boundaries need mocks: Apex, UI API wire adapters, navigation, LMS, or labels?
- Is the current test pain a setup problem, a mocking problem, or an assertion problem?

---

## Core Concepts

Jest unit tests run in Node and use mocks instead of live Salesforce services. That means a good test verifies behavior at the component boundary, not whether the real platform is present. Most flaky tests fail because they mix production mental models with a mocked unit-test runtime.

### Test Behavior, Not Private Implementation

The test should render the component, drive the public interaction, and assert visible behavior or emitted events. A test that knows too much about private fields or incidental DOM structure becomes brittle during harmless refactors.

### Async Rerendering Must Be Awaited Intentionally

LWC rerendering is asynchronous. After setting properties, emitting wire values, or resolving promises, the test must wait for microtasks before asserting the DOM. Many "random" failures are simply assertions that run before the component has had a chance to rerender.

### Wire And Imperative Apex Use Different Mocking Patterns

A wired Apex method or wire adapter should use the appropriate wire test utilities and emitted values. Imperative Apex calls should be mocked as module functions that resolve or reject promises. Mixing those patterns creates confusing tests that do not reflect the component's actual contract.

### Base Components And Platform Services Are Test Doubles

`lightning-*` base components are stubs in Jest. Navigation, toasts, labels, and many platform modules are mocked. That is expected. The test should focus on your component behavior, not on reproducing the entire browser-plus-Salesforce runtime.

---

## Common Patterns

### Render, Interact, Assert

**When to use:** The component behavior is driven by user actions or reactive property updates.

**How it works:** Create the element, append it to `document.body`, simulate the user action, wait for rerender, then assert the visible state or dispatched event.

**Why not the alternative:** Snapshot-only tests or direct private-field assertions tend to miss the actual behavior users care about.

### Wire Adapter Emission Testing

**When to use:** A component reads data through `@wire`.

**How it works:** Register the test wire adapter, create the component, emit data or error payloads, and assert both the happy path and the error state after the rerender boundary.

**Why not the alternative:** Mocking the rendered HTML without exercising the wire contract gives false confidence.

### Imperative Apex Promise Testing

**When to use:** A component saves or refreshes data through an imperative Apex call.

**How it works:** Mock the imported Apex module with `jest.mock`, resolve and reject the promise intentionally, and assert loading, success, and failure behavior.

**Why not the alternative:** Treating an imperative method like a wire adapter hides the actual async behavior and error path.

---

## Decision Guidance

| Situation | Recommended Approach | Reason |
|---|---|---|
| Component only needs a render or interaction check | `createElement` plus DOM assertions | Fastest path to behavior coverage |
| Component uses a wire adapter or wired Apex | Register and emit from a test wire adapter | Mirrors the reactive contract of the component |
| Component calls Apex imperatively | `jest.mock` the module and resolve or reject promises | Matches the import's imperative usage |
| Component navigates or fires platform events | Mock the platform module and assert invocation | Unit tests should verify intent, not real container behavior |
| Team is relying on snapshots as primary coverage | Replace with behavioral assertions | Snapshots rarely prove business behavior well |

---


## Recommended Workflow

Step-by-step instructions for an AI agent or practitioner activating this skill:

1. Gather context — confirm the org edition, relevant objects, and current configuration state
2. Review official sources — check the references in this skill's well-architected.md before making changes
3. Implement or advise — apply the patterns from Core Concepts and Common Patterns sections above
4. Validate — run the skill's checker script and verify against the Review Checklist below
5. Document — record any deviations from standard patterns and update the template if needed

---

## Review Checklist

Run through these before marking work in this area complete:

- [ ] The project includes `@salesforce/sfdx-lwc-jest` and a runnable unit-test script.
- [ ] Each important component has tests for success and failure paths, not only happy render.
- [ ] Wire adapters and imperative Apex calls use the correct mocking pattern.
- [ ] Tests wait for rerender or promise completion before asserting DOM state.
- [ ] `afterEach` cleanup removes mounted elements from `document.body`.
- [ ] Assertions target behavior that users or consumers rely on.

---

## Salesforce-Specific Gotchas

Non-obvious platform behaviors that cause real production problems:

1. **LWC rerenders after the current microtask** - assertions immediately after a click or `emit()` often run too early.
2. **Imperative Apex and wired Apex are not mocked the same way** - using a wire utility for an imperative import produces misleading tests.
3. **Base components are stubs in Jest** - the test should not assume exact runtime markup from the live platform.
4. **Platform modules such as navigation or toast are mocked boundaries** - assert that your component asked for the action, not that the container performed it.

---

## Output Artifacts

| Artifact | Description |
|---|---|
| Test plan | Coverage strategy for render, interaction, wire, Apex, and error paths |
| Jest review findings | Missing mocks, flaky async patterns, weak assertions, or setup gaps |
| Test scaffold | Reusable test skeleton with cleanup, mocks, and rerender handling |

---

## Related Skills

- `lwc/wire-service-patterns` - use when the real bug is the data contract rather than the test harness.
- `lwc/lifecycle-hooks` - use when timing or cleanup bugs exist in production as well as tests.
- `lwc/component-communication` - use when the component contract itself is hard to test because the communication design is wrong.

Related Skills

omnistudio-testing-patterns

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when testing or validating OmniStudio components — OmniScript preview, Integration Procedure step debugging, DataRaptor field-mapping validation, and end-to-end UTAM-based automation. NOT for Apex unit testing or standard Flow debugging.

lwc-jest-testing-with-accessibility

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when authoring or reviewing Jest unit tests for Lightning Web Components and the test plan must include explicit accessibility assertions — covers `@salesforce/sfdx-lwc-jest` setup, `createElement` / `document.body.appendChild` render harness, wire-service mocks via `@salesforce/wire-service-jest-util`, imperative Apex mocks via `jest.fn()`, simulated user interactions (`click`, `keydown`, `focus`), ARIA attribute and accessible-name assertions, focus-management tests, keyboard-navigation tests, and optional `axe-core` integration via `jest-axe`. Triggers: 'add a11y assertions to my LWC jest tests', 'how do I test focus management in LWC', 'jest test for keyboard navigation', 'integrate axe-core into sfdx-lwc-jest', 'assert ARIA attributes after interaction', 'how do I prove the LWC is accessible in CI'. NOT for general LWC jest setup without an a11y angle (use lwc/lwc-testing — this skill is the accessibility-deep-dive sibling), NOT for accessibility-pattern authoring inside the component itself (use lwc/lwc-accessibility-patterns), NOT for end-to-end UI automation via UTAM, NOT for manual screen-reader QA workflows.

flow-testing

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when defining or reviewing test strategy for Salesforce Flow, including Flow Tests, debug runs, path coverage, test data, and explicit validation of fault paths and custom component behavior. Triggers: 'flow test tool', 'how do i test a flow', 'flow fault path testing', 'flow debug interview'. NOT for Apex unit testing or manual QA planning that is unrelated to Flow behavior.

performance-testing-salesforce

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when planning or executing load tests, stress tests, or performance benchmarks against a Salesforce org. Covers Salesforce Scale Test, third-party tools (JMeter, BlazeMeter, k6), API throughput testing, Experience Page Time (EPT) measurement, and sandbox sizing for performance work. Triggers: 'load test Salesforce org', 'Scale Test Full Copy sandbox', 'EPT optimization', 'API concurrency limits', 'JMeter Salesforce performance'. NOT for Apex unit test performance assertions, LWC Jest tests, query optimization (see data/soql-query-optimization), or NFR definition (see architect/nfr-definition-for-salesforce).

data-seeding-for-testing

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when creating test data for scratch orgs, sandboxes, or CI pipelines: Apex @testSetup factories, sf data import tree plans, CumulusCI datasets, Snowfakery. NOT for production data migration or ETL pipelines.

continuous-integration-testing

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when configuring Apex test execution in CI/CD pipelines, choosing test levels for deployments, parsing test results, or troubleshooting code coverage in automated builds. Triggers: 'RunLocalTests', 'RunSpecifiedTests', 'sf project deploy', 'code coverage CI', 'JUnit test results'. NOT for Apex test class design patterns, test data factory architecture, or LWC Jest testing.

automated-regression-testing

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when building or maintaining automated end-to-end regression tests for Salesforce UI (Lightning, LWC, Aura, Flows), selecting a testing framework (UTAM, Provar, Selenium), handling Shadow DOM challenges, or scheduling regression suites against pre-release orgs. Triggers: 'UTAM page objects', 'Shadow DOM testing', 'Salesforce E2E regression', 'Provar test automation', 'pre-release regression window'. NOT for Apex unit testing, LWC Jest component testing, manual UAT planning, or Agentforce conversational testing.

agentforce-testing-strategy

8
from PranavNagrecha/AwesomeSalesforceSkills

Design Agentforce testing: topic coverage, action unit tests, deterministic golden sets, adversarial prompts, and regression harness. Trigger keywords: agentforce testing, agent eval, agent regression suite, prompt golden set, action unit test agentforce. Does NOT cover: generic LLM evaluation academia, human-labeled RLHF pipelines, or Einstein Classify accuracy.

agent-testing-and-evaluation

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when testing, evaluating, or building regression suites for Agentforce agents: conversation testing in Agent Builder, topic coverage and utterance testing, Testing API and AiEvaluationDefinition metadata, evaluation metrics (containment rate, escalation rate, CSAT, topic activation accuracy), and post-deploy analytics via Enhanced Event Logs. Triggers: 'how do I test my Agentforce agent', 'agent routes to wrong topic', 'write utterance tests', 'regression test after topic change', 'measure agent quality', 'agent containment rate'. NOT for agent creation, topic design, or action contract design — use agentforce/agentforce-agent-creation, agentforce/agent-topic-design, or agentforce/agent-actions respectively.

xss-and-injection-prevention

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when writing or reviewing Visualforce pages, Apex controllers, or LWC components that output user-supplied data, build dynamic queries, or construct HTTP responses. Triggers: 'XSS in Visualforce', 'SOQL injection vulnerability', 'how to encode output in Apex', 'JSENCODE Visualforce', 'open redirect prevention'. NOT for Apex CRUD/FLS enforcement (use soql-security or apex-crud-and-fls), NOT for Shield encryption (use shield-encryption-key-management), NOT for AppExchange security review process (use secure-coding-review-checklist).

visualforce-security-and-modernization

8
from PranavNagrecha/AwesomeSalesforceSkills

Use when hardening or modernizing legacy Visualforce pages — covers the platform CSRF token model and when disabling it is a security regression, view state encryption guarantees and the 170 KB ceiling, FLS/CRUD enforcement gaps on `<apex:outputField>` and on getters that return sObjects, `<apex:includeScript>` interaction with the org Content Security Policy, hosting LWC inside a VF page via `lightning:container` / `lightning-out`, and the retire-vs-harden-vs-leave-alone decision for an inventory of legacy pages. Triggers: 'should I rewrite this Visualforce page in LWC', 'CSRF protection disabled on Visualforce page is that safe', 'community user sees a field they should not on a Visualforce page', 'view state encryption is that enough for sensitive data', 'how do I host an LWC inside a Visualforce page', 'apex:dynamicComponent and apex:actionFunction safe to keep'. NOT for greenfield Visualforce architecture (use apex/visualforce-fundamentals — controller types, view state pattern selection, PDF rendering); NOT for Visualforce email template authoring (use apex/visualforce-email-templates if/when that skill is authored); NOT for general Apex security review across triggers and async (use apex/soql-security and security/secure-coding-review-checklist).

transaction-security-policies

8
from PranavNagrecha/AwesomeSalesforceSkills

Transaction Security policy creation and configuration: condition builder, enhanced policies, enforcement actions (block, MFA, notification, end session), real-time monitoring mode, and policy troubleshooting. NOT for Event Monitoring log analysis or Shield Event Monitoring setup (use event-monitoring). NOT for Apex testing or debug-log analysis.