Sub topic 8
Test public properties and methods
A Lightning web component's public API is its @api properties and methods. Parent components and tests reach the component only through that API, so tests of it describe the contract the component promises.
This chapter assumes you can already create a component with createElement, query its shadow root, and wait one microtask for re-rendering. It builds on the counter example from earlier chapters.
What counts as the public API
In a test, the host element returned by createElement is the only handle you have. Its public surface contains:
- Fields and accessors marked
@api, which you read and write like ordinary properties. - Methods marked
@api, which you call like ordinary functions. - Events the component dispatches. The next chapter covers those.
Anything not marked @api is private. A test can't read it through the element and shouldn't try to. If a private field matters, test its visible effect in the rendered output.
A component with a richer API
The counter's step property is simple. To show the edge cases, this chapter uses a quantity picker. It has two plain public fields (min and max), a public getter and setter pair (value) that clamps its input, and two public methods.
The template, force-app/main/default/lwc/quantityPicker/quantityPicker.html:
<template>
<p class="value">{value}</p>
</template>The class, quantityPicker.js:
import { LightningElement, api } from 'lwc';
export default class QuantityPicker extends LightningElement {
@api min = 0;
@api max = 10;
_value = 0;
@api
get value() {
return this._value;
}
set value(newValue) {
const number = Number(newValue);
if (Number.isNaN(number)) {
this._value = this.min;
return;
}
this._value = Math.min(this.max, Math.max(this.min, number));
}
@api
increment() {
this.value = this._value + 1;
return this._value;
}
@api
reset() {
this._value = this.min;
}
}The setter clamps the value using the current min and max. That makes the order in which a parent sets properties matter, and the tests below cover this.
How a property change flows
Setting a property from a test follows the same path as a parent component setting it in its template. The component's setter runs synchronously. The re-render happens later, in a microtask.
This gives you a rule for choosing what to await:
- Reading the property back needs no wait, because the getter reflects the setter immediately.
- Reading the rendered DOM needs
await Promise.resolve()after any change made once the element is attached.
A helper to build the component
Several tests need the same setup. A small helper keeps them short:
import { createElement } from 'lwc';
import QuantityPicker from 'c/quantityPicker';
function mount(props = {}) {
const element = createElement('c-quantity-picker', { is: QuantityPicker });
Object.assign(element, props);
document.body.appendChild(element);
return element;
}
describe('c-quantity-picker', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
// tests go here
});Object.assign sets properties in the order the keys appear in the object. Passing { max: 5, value: 8 } sets max first, which is what the clamping setter needs. Setting properties before appendChild also mirrors how a parent template works: the values are in place before the first render.
Test default values
A default is part of the contract, so give it a test. Create the element with no properties and read them back:
it('exposes documented defaults', () => {
const element = mount();
expect(element.min).toBe(0);
expect(element.max).toBe(10);
expect(element.value).toBe(0);
});The test needs no await because it reads properties, not the DOM.
Test values set before attaching
Initial values set before appendChild are the most common case. Check the property and the rendered result together:
it('clamps an initial value above max', async () => {
const element = mount({ max: 5, value: 8 });
expect(element.value).toBe(5);
expect(element.shadowRoot.querySelector('.value').textContent).toBe('5');
});This test has no await and still passes. The first render happens synchronously inside appendChild, so the DOM is already correct. You only need to wait for changes made after the element is attached.
Test values changed after attaching
Changing a property on a connected element triggers a re-render. Wait before reading the DOM:
it('re-renders when value is changed after attaching', async () => {
const element = mount();
element.value = 7;
await Promise.resolve();
expect(element.value).toBe(7);
expect(element.shadowRoot.querySelector('.value').textContent).toBe('7');
});Remove the await and the text assertion fails, because the DOM still shows 0. That failure is the usual sign of a missing wait.
Test setters and edge cases
A getter and setter pair is where most logic in a public property lives. Cover the boundaries, bad input, and the order dependence:
it('falls back to min when the input is not a number', () => {
const element = mount({ min: 2, value: 'abc' });
expect(element.value).toBe(2);
});
it('clamps below min', () => {
const element = mount({ min: 3, value: -4 });
expect(element.value).toBe(3);
});
it('depends on the order in which properties are set', () => {
const element = mount({ value: 8, max: 5 });
// value was clamped against the default max of 10 before max changed
expect(element.value).toBe(8);
expect(element.max).toBe(5);
});The third test documents a real weakness of this component. A parent that sets value before max ends up with a value above the maximum. The test records the current behavior. If you decide to fix it, for example by re-clamping in a max setter, you change this test along with the code.
Test public methods
Call a public method on the host element. Check its return value, its effect on state, and its effect on the DOM:
it('increment returns the new value and updates the DOM', async () => {
const element = mount();
const result = element.increment();
await Promise.resolve();
expect(result).toBe(1);
expect(element.value).toBe(1);
expect(element.shadowRoot.querySelector('.value').textContent).toBe('1');
});
it('increment stops at max', () => {
const element = mount({ max: 1 });
element.increment();
const result = element.increment();
expect(result).toBe(1);
});
it('reset returns the value to min', () => {
const element = mount({ min: 1, value: 4 });
element.reset();
expect(element.value).toBe(1);
});The return value of a method is available at once. Only the DOM needs the wait.
Object values are read-only
When a test assigns an object or array to a public property, the component receives a read-only view of it. If the component tries to modify that value in place, LWC throws an error. For example, this.items.push(x) fails when items came in through @api. A component that needs to change the data should copy it first. A test can assert the copying behavior by checking that the original object is unchanged after the component runs.
What to test, and how
| API element | Check | Wait needed? |
|---|---|---|
| Default value | Read the property on a fresh element | No |
| Value set before attaching | Read the property, then the DOM | No |
| Value set after attaching | Read the property, then the DOM | Yes, for the DOM |
| Getter and setter logic | Boundaries, invalid input, property order | No |
| Method return value | Capture and assert the result | No |
| Method side effect on the DOM | Query the shadow root | Yes |
Common mistakes
- Reading the DOM right after changing a connected component's property, without awaiting.
- Testing private fields such as
_valuethrough the element. They are not reachable, so assert on the public property or the DOM instead. - Relying on
Object.assignkey order without realizing it. If order matters to the component, write a test for it. - Forgetting the cleanup in
afterEach, so elements from earlier tests stay indocument.bodyand make DOM queries ambiguous.
Exercise
Add a test for the counter component from the earlier chapters. Create a c-counter with step set to 3, click its button twice, wait for re-rendering, and assert the text of the .count element. What value do you expect, and where must the await go?
Show answer
The expected text is '6', because each click adds the step of 3 to the count. Set element.step = 3 before document.body.appendChild(element). Click the button twice with element.shadowRoot.querySelector('button').click(), then put await Promise.resolve() after the second click and before the assertion. Assert expect(element.shadowRoot.querySelector('.count').textContent).toBe('6'). One wait after both clicks is enough, because the framework batches both state changes into a single re-render.
Exercise
In the quantity picker, element.max = 3 is assigned after the element is attached while value is 8 and max was 10. What do element.value and the rendered text show after await Promise.resolve(), and why?
Show answer
Both still show 8. max is a plain public field with no setter logic, so changing it does not re-clamp value. Only the value setter clamps, and it runs only when value is assigned. Fixing this needs a getter and setter on max that re-applies the clamp.