Sub topic 11
Asserting call arguments and wire config
Earlier chapters showed how to feed data into a component. This chapter covers the other direction: checking what the component asked for. A component can render the right output and still send the wrong search term to Apex, or wire to the wrong record. Assertions on call arguments and wire config catch those bugs.
This chapter assumes you can already create a component with createElement, flush promises, and mock a wired or imperative Apex method as shown in the previous chapters.
Two kinds of "input" to check
A component sends data outward in two ways, and each has its own assertion tool.
| Data source | What the component sends | How you read it in a test |
|---|---|---|
| Imperative Apex (`jest.fn`) | The parameters object passed when the method is called | `toHaveBeenCalledWith`, `mock.calls` |
| Wired Apex or built-in adapter | The config object resolved from `@wire` | `getLastConfig()` on the test wire adapter |
Imperative calls happen at a moment you trigger, such as a button click. Wire configs are computed by the framework whenever the component connects or a reactive parameter changes.
Asserting imperative Apex arguments
An imperative Apex import replaced by jest.fn() records every call. Apex methods in LWC take one argument, an object whose keys match the Apex parameter names. That object is what you assert on.
expect(findContacts).toHaveBeenCalledWith({ searchTerm: 'Amy' });Use toHaveBeenCalledWith when you care that at least one call used those arguments. Add toHaveBeenCalledTimes when the number of calls matters, for example to prove that a click triggers one server call and not two.
expect(findContacts).toHaveBeenCalledTimes(1);
expect(findContacts).toHaveBeenCalledWith({ searchTerm: 'Amy' });Checking a specific call
When a component calls the same method several times, inspect mock.calls. It is an array with one entry per call, and each entry is the list of arguments for that call. Because LWC passes a single object, the parameters object is mock.calls[n][0].
const firstParams = findContacts.mock.calls[0][0];
const lastParams = findContacts.mock.calls[findContacts.mock.calls.length - 1][0];
expect(firstParams.searchTerm).toBe('Am');
expect(lastParams.searchTerm).toBe('Amy');Jest also provides toHaveBeenLastCalledWith and toHaveBeenNthCalledWith(n, ...). These read more clearly than indexing into mock.calls and give better failure messages.
Checking that Apex was not called
Some behavior is defined by what does not happen. A component might skip the server call when the input is empty. Assert that directly.
expect(findContacts).not.toHaveBeenCalled();This assertion is only meaningful if no earlier test left calls on the mock. See the isolation section below.
How equality works
toHaveBeenCalledWith compares arguments by value, recursively, so { searchTerm: 'Amy' } matches a different object with the same contents. Two points matter in practice:
- Extra keys cause a mismatch. If the component sends
{ searchTerm: 'Amy', limitCount: 10 }, the assertion above fails. - Properties whose value is
undefinedare treated as absent, so{ searchTerm: 'Amy', limitCount: undefined }matches{ searchTerm: 'Amy' }.
When you only care about part of the parameters, use an asymmetric matcher.
expect(findContacts).toHaveBeenCalledWith(
expect.objectContaining({ searchTerm: 'Amy' })
);Prefer the exact form by default. A loose match can hide the case where the component starts sending an unexpected extra parameter.
A full imperative example
This test checks the arguments, the call count, and that an empty search does not reach the server. It assumes a c-contact-search component that calls findContacts when the button is clicked and skips the call for a blank term.
import { createElement } from 'lwc';
import ContactSearch from 'c/contactSearch';
import findContacts from '@salesforce/apex/ContactController.findContacts';
jest.mock(
'@salesforce/apex/ContactController.findContacts',
() => ({ default: jest.fn() }),
{ virtual: true }
);
const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 0));
describe('c-contact-search call arguments', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
jest.clearAllMocks();
});
it('sends the typed term exactly once', async () => {
findContacts.mockResolvedValue([]);
const element = createElement('c-contact-search', { is: ContactSearch });
document.body.appendChild(element);
const input = element.shadowRoot.querySelector('lightning-input');
input.value = 'Amy';
input.dispatchEvent(new CustomEvent('change'));
element.shadowRoot.querySelector('lightning-button').click();
await flushPromises();
expect(findContacts).toHaveBeenCalledTimes(1);
expect(findContacts).toHaveBeenCalledWith({ searchTerm: 'Amy' });
});
it('does not call Apex when the term is blank', async () => {
const element = createElement('c-contact-search', { is: ContactSearch });
document.body.appendChild(element);
element.shadowRoot.querySelector('lightning-button').click();
await flushPromises();
expect(findContacts).not.toHaveBeenCalled();
});
});If the second test were run without jest.clearAllMocks() in afterEach, the call from the first test would still be recorded and the not.toHaveBeenCalled() assertion would fail.
Asserting wire config
A wire does not receive a call from your code. The framework builds a config object from the @wire declaration and passes it to the adapter. For a declaration like this one, the config is { accountId: <current value> }.
@wire(getContactsByAccount, { accountId: '$accountId' })
contacts;The $ prefix marks a reactive parameter. The framework replaces '$accountId' with the current value of this.accountId and provisions the adapter again whenever that value changes.
The test wire adapters from createApexTestWireAdapter and from the lightning/uiRecordApi stubs expose getLastConfig(). It returns the most recent config the component supplied.
import { createElement } from 'lwc';
import ContactsByAccount from 'c/contactsByAccount';
import getContactsByAccount from '@salesforce/apex/ContactController.getContactsByAccount';
jest.mock(
'@salesforce/apex/ContactController.getContactsByAccount',
() => {
const { createApexTestWireAdapter } = require('@salesforce/sfdx-lwc-jest');
return { default: createApexTestWireAdapter(jest.fn()) };
},
{ virtual: true }
);
const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 0));
describe('c-contacts-by-account wire config', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('wires with the accountId and follows changes', async () => {
const element = createElement('c-contacts-by-account', {
is: ContactsByAccount
});
element.accountId = '001A';
document.body.appendChild(element);
await flushPromises();
expect(getContactsByAccount.getLastConfig()).toEqual({ accountId: '001A' });
element.accountId = '001B';
await flushPromises();
expect(getContactsByAccount.getLastConfig()).toEqual({ accountId: '001B' });
});
});The second assertion checks reactivity. If the component accidentally used a plain value accountId: this.accountId in a getter that is not tracked, or dropped the $, the config would not follow the property and this test would fail.
The same technique for built-in adapters
The getRecord stub from lightning/uiRecordApi also has getLastConfig(). Use it to confirm that the component wired to the record you passed in.
expect(getRecord.getLastConfig()).toEqual(
expect.objectContaining({ recordId: '001000000000001AAA' })
);Using objectContaining here is deliberate. The fields entry in a getRecord config holds resolved schema references, and a test that spells them out is brittle. Assert the pieces you care about.
What wire config assertions do not cover
getLastConfig() tells you what the component asked for. It does not call the adapter's real logic. Apex-specific behavior such as caching with cacheable=true, or whether the server accepts the parameter names, belongs to Apex tests and integration testing. Your Jest test proves only that the component produces the right config.
Keep one more limit in mind: the test checks the name of each key in the config, but nothing checks that it matches the Apex parameter name. If the Apex method takes accountId and the component wires { accountID: '$accountId' }, a Jest test that asserts the same wrong key will pass. Take the expected keys from the Apex method signature, not from the component.
Choosing the right assertion
- Use
toHaveBeenCalledWithfor the parameters of an imperative call triggered by a user action. - Use
toHaveBeenCalledTimesornot.toHaveBeenCalledfor how often the server is reached. - Use
getLastConfig()for what a wire was configured with, including after reactive changes. - Use
objectContainingwhen the full object includes values you do not control. - Combine argument assertions with a render assertion. Checking only the arguments proves the request was right, and checking only the output proves the response was handled. Together they cover both sides.
Exercise
A component declares @wire(getContactsByAccount, { accountId: '$accountId' }). A test sets element.accountId = '001A', appends the element, and asserts getContactsByAccount.getLastConfig() equals { accountId: '001A' }. The test then sets element.accountId = '001B' and asserts the config again, but the assertion still sees '001A'. What is the most likely cause in the test, and how do you fix it?
Show answer
The test reads the config before the framework has re-provisioned the wire. Reactive changes are applied asynchronously, so the test must wait with await flushPromises() after setting the new property and before calling getLastConfig(). If the wait is already there, check that the component really uses the $ prefix, because a plain accountId would never update.
Exercise
A test asserts expect(findContacts).not.toHaveBeenCalled() and passes alone but fails when the whole file runs. Another test in the file clicks a button that calls findContacts. What is missing, and what does jest.clearAllMocks() do and not do?
Show answer
The mock keeps its recorded calls across tests, so the earlier test's call is still visible. Add jest.clearAllMocks() to afterEach. It resets mock.calls and mock.results on every mock but keeps the implementations set with mockResolvedValue, so use jest.resetAllMocks() if you also need to remove those.
Exercise
The component sends { searchTerm: 'Amy', limitCount: 10 } and the test asserts toHaveBeenCalledWith({ searchTerm: 'Amy' }). The assertion fails. Give two ways to make the test express your intent.
Show answer
If the limit is part of the contract, assert the full object: toHaveBeenCalledWith({ searchTerm: 'Amy', limitCount: 10 }). If only the term matters, use expect.objectContaining({ searchTerm: 'Amy' }). Prefer the exact form unless the extra values are outside what this test is about.