Lightning Web Components (LWC) are built on standard web technology: HTML templates, modern JavaScript and web components. If you have written any front-end code, most of it will feel familiar. What's different is how a component gets Salesforce data and how it behaves on a Lightning page. This guide builds one small but complete component, a list of contacts on an Account page, and takes it all the way to tests.
The files in a component
A component is a folder with files that share its name. For a component called accountContacts:
| File | Purpose |
|---|---|
accountContacts.html | The template |
accountContacts.js | The logic |
accountContacts.js-meta.xml | Where the component can be used |
__tests__/accountContacts.test.js | Jest tests |
Component folder names use camelCase. In markup, the same component is written in kebab-case: <c-account-contacts>.
Step 1: The Apex method
The component needs contacts for the Account it sits on. To use an Apex method with @wire, it must be static, public or global, and annotated with @AuraEnabled(cacheable=true).
public with sharing class ContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContacts(Id accountId) {
return [
SELECT Id, Name, Title, Email
FROM Contact
WHERE AccountId = :accountId
WITH USER_MODE
ORDER BY Name
LIMIT 50
];
}
} WITH USER_MODE makes the query respect the running user's object and field access. with sharing makes it respect record sharing. Keep both, so the component never shows data the user shouldn't see.
Step 2: The metadata file
The metadata file decides where the component can be placed. This one can go on record pages.
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>62.0</apiVersion>
<isExposed>true</isExposed>
<masterLabel>Account Contacts</masterLabel>
<targets>
<target>lightning__RecordPage</target>
</targets>
<targetConfigs>
<targetConfig targets="lightning__RecordPage">
<objects>
<object>Account</object>
</objects>
</targetConfig>
</targetConfigs>
</LightningComponentBundle> Step 3: Wire the data
On a record page, Salesforce sets recordId for you if you declare it with @api. Pass it to the wire with a $ in front. The $ makes the parameter reactive, so the wire runs again whenever the value changes.
import { LightningElement, api, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class AccountContacts extends LightningElement {
@api recordId;
contacts;
error;
wiredResult;
@wire(getContacts, { accountId: '$recordId' })
wiredContacts(result) {
this.wiredResult = result;
const { data, error } = result;
if (data) {
this.contacts = data;
this.error = undefined;
} else if (error) {
this.contacts = undefined;
this.error = getErrorMessage(error);
}
}
get isLoading() {
return !this.contacts && !this.error;
}
get hasContacts() {
return this.contacts && this.contacts.length > 0;
}
async handleRefresh() {
await refreshApex(this.wiredResult);
}
}
function getErrorMessage(error) {
if (Array.isArray(error.body)) {
return error.body.map((e) => e.message).join(', ');
}
if (error.body && typeof error.body.message === 'string') {
return error.body.message;
}
return error.message || 'Unknown error';
} A few details worth knowing:
- The parameter object's keys must match the Apex parameter names. Here,
accountId. - The wire function always receives an object with
dataorerror. Those names are fixed. - We keep the whole
resultinwiredResultso we can pass it torefreshApexlater. - Errors from Apex can arrive with
bodyas an object or an array. The small helper handles both.
Step 4: The template
Every component should handle three states: loading, error and data. Showing a blank box while data loads, or on failure, confuses users.
<template>
<lightning-card title="Contacts" icon-name="standard:contact">
<lightning-button-icon
slot="actions"
icon-name="utility:refresh"
alternative-text="Refresh contacts"
onclick={handleRefresh}
></lightning-button-icon>
<div class="slds-p-horizontal_medium">
<template lwc:if={isLoading}>
<lightning-spinner alternative-text="Loading contacts" size="small"></lightning-spinner>
</template>
<template lwc:elseif={error}>
<p class="slds-text-color_error">{error}</p>
</template>
<template lwc:elseif={hasContacts}>
<ul class="slds-has-dividers_bottom-space">
<template for:each={contacts} for:item="contact">
<li key={contact.Id} class="slds-item">
<p class="slds-text-title_bold">{contact.Name}</p>
<p>{contact.Title}</p>
<p>{contact.Email}</p>
</li>
</template>
</ul>
</template>
<template lwc:else>
<p>No contacts on this account yet.</p>
</template>
</div>
</lightning-card>
</template> Wire or imperative?
@wire is the default choice for reading data. The framework calls the method for you, caches the result and calls again when parameters change.
Call Apex imperatively when:
- You need to control when the call happens, like on a button click
- The method changes data (insert, update or delete), so it can't be
cacheable=true - You are calling from a module that doesn't extend
LightningElement
import markPrimary from '@salesforce/apex/ContactController.markPrimary';
async handleMarkPrimary(event) {
try {
await markPrimary({ contactId: event.target.dataset.id });
this.error = undefined;
await refreshApex(this.wiredResult);
} catch (error) {
this.error = getErrorMessage(error);
}
} markPrimary is an example method that updates a record, so it would not be cacheable. After it runs, refreshApex reloads the wired list so the screen shows the change.
💡 Don't overload @AuraEnabled methods
If two @AuraEnabled methods share a name with different parameters, the one that gets called is effectively random. Give every method a unique name.
Step 5: Set up Jest
Jest tests run on your machine, not in a browser and not in an org. They are fast enough to run every time you save. From the top folder of your Salesforce DX project:
npm install
npm install @salesforce/sfdx-lwc-jest --save-dev Then add these scripts to package.json if they aren't there yet:
"scripts": {
"test": "npm run test:unit",
"test:unit": "sfdx-lwc-jest",
"test:unit:watch": "sfdx-lwc-jest --watch",
"test:unit:debug": "sfdx-lwc-jest --debug",
"test:unit:coverage": "sfdx-lwc-jest --coverage"
} Step 6: Write the tests
Tests live in a __tests__ folder inside the component. To test a wired Apex method, mock it with a test wire adapter and push data or errors into it with emit() and error().
import { createElement } from 'lwc';
import AccountContacts from 'c/accountContacts';
import getContacts from '@salesforce/apex/ContactController.getContacts';
jest.mock(
'@salesforce/apex/ContactController.getContacts',
() => {
const { createApexTestWireAdapter } = require('@salesforce/sfdx-lwc-jest');
return { default: createApexTestWireAdapter(jest.fn()) };
},
{ virtual: true }
);
const MOCK_CONTACTS = [
{ Id: '003000000000001', Name: 'Asha Kumar', Title: 'CTO', Email: 'asha@example.com' },
{ Id: '003000000000002', Name: 'Ravi Shah', Title: 'Buyer', Email: 'ravi@example.com' }
];
describe('c-account-contacts', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
jest.clearAllMocks();
});
it('shows one list item per contact', async () => {
const element = createElement('c-account-contacts', { is: AccountContacts });
element.recordId = '001000000000001';
document.body.appendChild(element);
getContacts.emit(MOCK_CONTACTS);
await Promise.resolve();
const items = element.shadowRoot.querySelectorAll('li');
expect(items.length).toBe(2);
});
it('shows an error message when Apex fails', async () => {
const element = createElement('c-account-contacts', { is: AccountContacts });
document.body.appendChild(element);
getContacts.error();
await Promise.resolve();
const errorText = element.shadowRoot.querySelector('.slds-text-color_error');
expect(errorText).not.toBeNull();
});
}); The afterEach block clears the DOM between tests, so one test can't affect the next. await Promise.resolve() gives the component a moment to re-render after the mock data arrives.
Run the tests with npm run test:unit, or keep npm run test:unit:watch open while you work.
Before you ship
- Apex uses
with sharingandWITH USER_MODE - The component shows loading, error, empty and data states
- Every interactive element has an accessible label
- Data-changing calls are imperative and followed by
refreshApex - Jest tests cover data and error paths
- Apex tests cover the controller, since Jest doesn't test Apex