Skip to content

Instantly share code, notes, and snippets.

@joeythomaschaske
Last active May 3, 2022 03:51
Show Gist options
  • Save joeythomaschaske/6d93e984142299e6a01b277b0dc652da to your computer and use it in GitHub Desktop.
Save joeythomaschaske/6d93e984142299e6a01b277b0dc652da to your computer and use it in GitHub Desktop.
sfdx-lwc-jest utility for testing async functionality
global.waitFor = (expectationFunction) => {
const MAX_WAIT = 5000;
const POLL_INTERVAL = 100;
return new Promise((resolve, reject) => {
const startTime = Date.now();
let error;
const interval = setInterval(() => {
try {
if (Date.now() - startTime < MAX_WAIT) {
expectationFunction();
clearInterval(interval);
resolve();
} else {
clearInterval(interval);
reject(error);
}
} catch (e) {
error = e.matcherResult;
}
}, POLL_INTERVAL);
});
};
// in your test method call waitFor like this
const button = element.shadowRoot.querySelector('button');
button.dispatchEvent(new CustomEvent('click')); // calls an async handler
await waitFor(() => { expect(createUserKey.mock.calls.length).toBe(1) }); // wait for you mock to be called within the async handler
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment