Sub topic 8
Test public properties and methods
This chapter assumes you can write a basic Jest test with createElement, query the shadow root, and use await Promise.resolve() to wait for rendering. The examples use the c-counter component from earlier chapters.
What counts as the public API
A component's public API is everything marked @api: properties, getters and setters, and methods. A test sits outside the component, like a parent would. It can read and write only these members. Private fields such as count are not reachable from the test element, so you check them through the rendered DOM.
| Member | How a test uses it | What to assert |
|---|---|---|
| `@api` property | Assign `element.step = 2` | The DOM, events, or the value read back |
| `@api` getter/setter | Assign and read it | The computed result and any validation |
| `@api` method | Call `element.reset()` | The DOM or events after the call |
Add a public method
To have a method to test, add reset() to the counter class. It sets the count back to zero.
import { LightningElement, api } from 'lwc';
export default class Counter extends LightningElement {
@api step = 1;
count = 0;
@api
reset() {
this.count = 0;
}
handleClick() {
this.count += this.step;
this.dispatchEvent(
new CustomEvent('countchange', { detail: { count: this.count } })
);
}
}Test defaults, assignment, and methods
The tests below cover three things: the default value, a value set after the component is attached, and the public method.
import { createElement } from 'lwc';
import Counter from 'c/counter';
function createCounter(props = {}) {
const element = createElement('c-counter', { is: Counter });
Object.assign(element, props);
document.body.appendChild(element);
return element;
}
describe('c-counter public API', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('defaults step to 1', async () => {
const element = createCounter();
expect(element.step).toBe(1);
element.shadowRoot.querySelector('button').click();
await Promise.resolve();
expect(element.shadowRoot.querySelector('.count').textContent).toBe('1');
});
it('uses a step assigned after the component is attached', async () => {
const element = createCounter();
element.step = 5;
element.shadowRoot.querySelector('button').click();
await Promise.resolve();
expect(element.shadowRoot.querySelector('.count').textContent).toBe('5');
});
it('resets the count through the public method', async () => {
const element = createCounter({ step: 3 });
const button = element.shadowRoot.querySelector('button');
button.click();
await Promise.resolve();
element.reset();
await Promise.resolve();
expect(element.shadowRoot.querySelector('.count').textContent).toBe('0');
});
});The createCounter helper assigns properties before calling appendChild. This matches how a parent template works: values are set first, then the component connects. Setting a property after attaching, as in the second test, is also valid. It mimics a parent changing a value later.
Common errors
- Asserting before re-rendering. Calling a method or setting a property that changes tracked state does not update the DOM immediately. Wait with
await Promise.resolve()before you check the text. - Reading private state.
element.countisundefinedbecausecountis not@api. Assert on.countin the shadow DOM instead. - Mutating object values. If a parent passes an object or array to an
@apiproperty, the component receives a read-only proxy. Assigning to its fields throws. If a test passes data in, treat it as immutable and pass a new object to change it. - Using attribute names. In a template you write
step-size, but in a test you set the camelCase property,element.stepSize.
Test setters and getters
A public setter often validates or transforms its input. Test it with the same pattern: assign the value, wait one microtask, then check the output. Cover at least one valid input, one invalid input, and the default state when nothing is assigned.
Exercise
Why does the test for reset() call await Promise.resolve() after element.reset() and before reading the .count text?
Show answer
reset() changes the component's count field, and LWC re-renders asynchronously in a microtask. Without the wait, the test reads the DOM from before the update and still sees the old number.
Exercise
Add a test showing that element.count is not part of the public API, and say what the test expects.
Show answer
Create the counter, click the button, and await one microtask. Then expect(element.count).toBeUndefined(). count has no @api decorator, so the host element exposes no such property. To verify the count, read the .count paragraph in element.shadowRoot.