Sub topic 14
Testing and debugging site components
This chapter assumes you can write Jest tests at a basic level and can read the CaseList component from earlier chapters. It also assumes you have a Salesforce DX project and know how to create debug logs. You will test components with Jest, then debug the failures that only show up inside a running site.
Why site components need two kinds of testing
A site component runs in two places. Your code runs in a browser, where it depends on the site runtime, the visitor's identity, and Experience Builder. Its Apex runs on the server under the site user's permissions. Jest can check the first part in isolation. It cannot check sharing rules, guest access, or the Builder property editor.
Plan three layers.
Run the layers in order. A Jest failure takes seconds to find. A guest permission problem can take much longer.
Unit testing with Jest
Install the Salesforce LWC Jest tooling in your DX project, then run the tests:
npm install @salesforce/sfdx-lwc-jest --save-dev
npx sfdx-lwc-jest -- --coverageJest replaces Salesforce-specific imports such as @salesforce/apex/... and @salesforce/user/isGuest with stubs. Wire adapters need a test adapter so you can push data into the component yourself.
This test covers CaseList from the spine. It checks the rendered list, the maxRows config passed to the wire, and the empty state.
import { createElement } from 'lwc';
import CaseList from 'c/caseList';
import { registerApexTestWireAdapter } from '@salesforce/sfdx-lwc-jest';
import getMyCases from '@salesforce/apex/CaseListController.getMyCases';
const getMyCasesAdapter = registerApexTestWireAdapter(getMyCases);
function mount(props = {}) {
const element = createElement('c-case-list', { is: CaseList });
Object.assign(element, props);
document.body.appendChild(element);
return element;
}
describe('c-case-list', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('renders one list item per case', async () => {
const element = mount();
getMyCasesAdapter.emit([
{ Id: '5001', CaseNumber: '00001', Subject: 'Login fails' }
]);
await Promise.resolve();
const items = element.shadowRoot.querySelectorAll('li');
expect(items).toHaveLength(1);
expect(items[0].textContent).toBe('00001: Login fails');
});
it('passes maxRows from the page editor to the wire', async () => {
mount({ maxRows: 10 });
await Promise.resolve();
expect(getMyCasesAdapter.getLastConfig()).toEqual({ maxRows: 10 });
});
it('shows the empty message when no cases come back', async () => {
const element = mount();
getMyCasesAdapter.emit([]);
await Promise.resolve();
const message = element.shadowRoot.querySelector('p');
expect(message.textContent).toBe('No cases found.');
});
});Three details matter here:
- Setting
maxRowsbeforeappendChildmimics how Experience Builder sets a property before the component renders. await Promise.resolve()waits for the component to re-render after the adapter emits data.getLastConfig()shows the parameters the wire last used. This is how you verify a reactive'$maxRows'parameter.
Testing the guest branch
isGuest is a module-level import, so you cannot change it between tests in one file. Put the guest test in its own file and mock the module before the component loads.
import { createElement } from 'lwc';
import CaseList from 'c/caseList';
jest.mock('@salesforce/user/isGuest', () => ({ default: true }), {
virtual: true
});
describe('c-case-list as a guest', () => {
it('asks the visitor to log in', async () => {
const element = createElement('c-case-list', { is: CaseList });
document.body.appendChild(element);
await Promise.resolve();
const message = element.shadowRoot.querySelector('p');
expect(message.textContent).toBe('Log in to see your cases.');
});
});Do the same for error states. Call getMyCasesAdapter.error() and assert that your component shows something sensible instead of a blank area.
Testing the Apex side as site users
WITH USER_MODE enforces object, field, and record access for whoever runs the query. An Apex test that runs as an administrator will pass even when the query would fail for a site user. Run the method as a user with the profile your site uses, and set up the sharing that user would actually have.
@IsTest
private class CaseListControllerTest {
@IsTest
static void returnsOnlyRowsVisibleToTheUser() {
Profile p = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];
User u = new User(
Alias = 'tstusr', Email = '[email protected]',
EmailEncodingKey = 'UTF-8', LastName = 'Tester',
LanguageLocaleKey = 'en_US', LocaleSidKey = 'en_US',
TimeZoneSidKey = 'America/Los_Angeles', ProfileId = p.Id,
UserName = 'tstusr' + System.currentTimeMillis() + '@example.com'
);
insert u;
List<Case> result;
Test.startTest();
System.runAs(u) {
result = CaseListController.getMyCases(5);
}
Test.stopTest();
System.assert(result.size() <= 5, 'LIMIT must be respected');
}
}System.runAs can run as a standard internal user. It cannot run as a guest user, so use it to check the logic and the limit, and use the manual checks below for guest and external access.
Debugging inside a site
When a component works in Jest but misbehaves in the site, work from the symptom.
| Symptom | Likely cause | What to check |
|---|---|---|
| Component missing from the Builder component list | `isExposed` is `false`, a target is misspelled, or the deploy failed | Meta file targets (`lightningCommunity__Page`), deploy output |
| Property changes in Builder do nothing | Property not declared in `targetConfigs`, or no `@api` field with the same name | Property `name` matches the `@api` field exactly |
| Works for you, blank for visitors | The site was not published, or the guest profile lacks Apex class access | Publish status, guest user profile |
| Wire returns an error for guests only | Missing object or field permission, or `WITH USER_MODE` rejecting the query | Guest user profile and sharing rules |
| Old data after a change | Cacheable Apex or browser cache | Hard refresh, then check `cacheable=true` |
| Different behavior in LWR and Aura | Runtime differences | Re-check the feature against the runtime you use |
Browser tools
Open the browser developer tools on the preview or the published page. The Console shows errors from the framework and from your console.log calls. The Network tab shows the Apex requests and their responses, which tells you whether a failure came from the server or from rendering. In Aura sites, turn on debug mode for your user in Setup so that the browser receives readable, unminified code. Without it, stack traces are hard to follow.
Server-side logs
Create a debug log for the user whose access you are testing, then reproduce the problem. For visitors who are not logged in, add a trace flag for the site's guest user. The log shows the SOQL that ran, the user context, and any exception such as an insufficient-access error.
Testing identities
Check each identity that matters for your site:
- Builder preview. It is fast, but it runs as you, so it hides permission problems.
- Published site in a private browser window. This is the guest experience. Publish first, because guests never see unpublished changes.
- An external user. Log in as a real test user with the same profile and permission sets as real members, or use the administrator login-as feature for that user.
Exercise
Your Jest tests for CaseList all pass, but in the published site a guest sees "No cases found." instead of the login prompt. The guest branch test also passes. Name two places to look first.
Show answer
First, confirm the site was published after the latest deploy, because guests see only the published version. Second, check how isGuest is evaluated in the real runtime: open the page in a private window, check the browser console for errors, and confirm that you are testing as a guest and not as a logged-in user with a lingering session. The Jest mock of @salesforce/user/isGuest only proves the template reacts to the value. It does not prove the runtime supplies it.
Exercise
Why does an Apex test that calls getMyCases directly, without System.runAs, give weak evidence about site security?
Show answer
The test runs as the user who started it, usually with broad access, so WITH USER_MODE finds no restrictions. The test would pass even if the site user's profile or sharing blocked the query. Use System.runAs with a representative user for logic checks, and verify guest and external access manually in the published site.