Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 36 ยท Lightning Web Components

LWC Lifecycle Hooks and Jest Testing

Learn the LWC lifecycle: constructor, connectedCallback, renderedCallback and disconnectedCallback, then test components with Jest, with runnable JavaScript stand-ins.

Every Lightning Web Component goes through a life: it is created, inserted into the page, rendered, perhaps re-rendered many times, and finally removed. Lifecycle hooks are methods the framework calls at each stage. Knowing the order lets you load data at the right time and clean up properly. The second half of this lesson shows how to unit test components with Jest, the JavaScript test runner Salesforce provides in @salesforce/sfdx-lwc-jest. It builds on events and calling Apex.

LWC needs Salesforce tooling, so LWC and Jest listings are read-only. The runnable examples are plain JavaScript stand-ins for the lifecycle order and for the arrange-act-assert shape of a component test.

The hooks in order

Hook When it runs Typical use
constructor() The component instance is created Set defaults. Call super() first. Do not read attributes or children
connectedCallback() Inserted into the DOM Load data, subscribe to channels, add listeners
render() Optional; chooses which template to show Switch templates
renderedCallback() After every render Work with the rendered DOM (focus, third-party libraries)
disconnectedCallback() Removed from the DOM Unsubscribe, clear timers
errorCallback(error, stack) A child throws Show a fallback

Parents run before children when going down (constructor, connected, render), and children finish rendering before the parent's renderedCallback.

JavaScript
import { LightningElement } from 'lwc';

export default class Clock extends LightningElement {
    now = new Date().toLocaleTimeString();
    timerId;

    connectedCallback() {
        this.timerId = setInterval(() => {
            this.now = new Date().toLocaleTimeString();
        }, 1000);
    }

    disconnectedCallback() {
        clearInterval(this.timerId);   // otherwise the timer leaks
    }
}

renderedCallback runs a lot

renderedCallback fires after every render, including renders triggered by changes you make in it. Guard one-time work with a flag, and never set tracked fields in it without a condition, or you can loop forever.

JavaScript
renderedCallback() {
    if (this.initialised) {
        return;
    }
    this.initialised = true;
    this.template.querySelector('input').focus();
}

Querying the DOM

Use this.template.querySelector() (not document.querySelector) so you only reach elements owned by your component, and only after render. Elements you add with lwc:dom="manual" can be filled by third-party libraries.

Testing with Jest

Salesforce DX projects can include Jest. You create __tests__/accountCard.test.js inside the component folder. Tests render the component with createElement, attach it to the DOM, change inputs, and assert on the output.

JavaScript
import { createElement } from 'lwc';
import AccountCard from 'c/accountCard';

describe('c-account-card', () => {
    afterEach(() => {
        while (document.body.firstChild) {
            document.body.removeChild(document.body.firstChild);
        }
    });

    it('shows the account name', async () => {
        const element = createElement('c-account-card', { is: AccountCard });
        element.name = 'Globex';
        document.body.appendChild(element);

        await Promise.resolve();   // wait for the re-render

        const p = element.shadowRoot.querySelector('p');
        expect(p.textContent).toBe('Name: Globex');
    });
});

Key points:

  • Changes to a component re-render asynchronously, so await Promise.resolve() before asserting.
  • You read the output through element.shadowRoot.
  • Clean the DOM after each test.
  • Apex calls are mocked: jest.mock('@salesforce/apex/AccountController.getTopAccounts', () => ({ default: jest.fn() }), { virtual: true }); then getTopAccounts.mockResolvedValue([...]). Wire adapters have test helpers such as createApexTestWireAdapter and the @salesforce/sfdx-lwc-jest emit methods.
  • Run all tests with npm run test:unit (or sfdx-lwc-jest).

Jest tests are fast and need no org, so use them for logic and rendering, and save org tests for Apex.

Try the idea: lifecycle order (JavaScript stand-in)

JS Stand-in: parent and child hook order (JavaScript)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice the child's renderedCallback runs before the parent's, as in the real framework.

Try the idea: a component test with a fake DOM (JavaScript stand-in)

JS Stand-in: arrange, act, await the re-render, assert (JavaScript)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first expect shows why real tests must await: the DOM updates in a microtask, not immediately.

Debugging tips

  • console.log appears in the browser console; Salesforce also offers Lightning Debug Mode (Setup, Debug Mode) for unminified code and better warnings.
  • If a wire returns nothing, check the parameter spelling and that the $ property is defined before first render.
  • Prefer connectedCallback for loading and renderedCallback only for DOM work.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should you subscribe to a message channel and where should you unsubscribe?

    connectedCallback runs when the component is added to the page and disconnectedCallback when it is removed, which pairs setup with cleanup.
  2. 2. Why guard code in renderedCallback with a flag?

    renderedCallback fires after each render, including renders it causes itself.
  3. 3. In a Jest test, why do you await Promise.resolve() after changing a property?

    LWC re-renders in a microtask, so assertions must wait for it.
  4. 4. How do you read the rendered output of a component under test?

    The component's output lives in its shadow root, so query through element.shadowRoot.

Summary

  • Hooks run in order: constructor, connectedCallback, render, renderedCallback, disconnectedCallback.
  • Set up in connectedCallback, clean up in disconnectedCallback; guard renderedCallback.
  • Jest tests render with createElement, await the re-render and query shadowRoot; Apex and wires are mocked.

Next: Making REST Callouts and Mocking Them