Testing Strategy and Jest Fundamentals
By the end of this lesson, you'll be able to:
- Explain why automated component tests catch regressions faster than manual clicking
- Understand the sfdx-lwc-jest testing setup
- Write a basic Jest test that renders a component and asserts its output
Prerequisites: Module 13: "Debugging Performance Problems"
Why Test LWC Components?
Manually re-clicking through a component in a real org after every change is slow, easy to skip under deadline pressure, and doesn't scale as a component grows. An automated test runs in seconds, runs the same way every time, and catches a regression the moment it's introduced — long before a user ever sees it.
Jest and sfdx-lwc-jest
Salesforce provides sfdx-lwc-jest, tooling built on the popular Jest testing framework, configured specifically to run LWC component tests. Critically, these tests run entirely locally (or in CI) with no connection to a real Salesforce org — they test a component's own rendering and JavaScript logic in isolation.
Anatomy of a Basic Test
import { createElement } from 'lwc';
import HelloSalesforce from 'c/helloSalesforce';
describe('c-hello-salesforce', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('renders a greeting', () => {
const element = createElement('c-hello-salesforce', { is: HelloSalesforce });
document.body.appendChild(element);
const paragraph = element.shadowRoot.querySelector('p');
expect(paragraph.textContent).toBe('Hello, Salesforce!');
});
});
createElement builds an instance of the component (from Module 1's "Hello Salesforce" project); appendChild inserts it into a test DOM so it actually renders; element.shadowRoot.querySelector reads its rendered output (Module 1's Shadow DOM concept, now used to make assertions); afterEach cleans up between tests so they don't interfere with each other.
Exercise
Write a Jest test asserting that a c-welcome-banner component renders an h1 with the text "Welcome".
Show hint
Follow the createElement/appendChild/querySelector pattern shown above.
Exercise
Challenge: explain, as a comment, why sfdx-lwc-jest tests can run without any connection to a real Salesforce org.
Show hint
Think about what these tests are actually exercising.
Testing Strategy and Jest Fundamentals Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
Jest tests for LWC run entirely locally, with no org connection needed — catching regressions in seconds rather than by manually clicking through a deployed component every time.