Last active
May 3, 2022 03:51
-
-
Save joeythomaschaske/6d93e984142299e6a01b277b0dc652da to your computer and use it in GitHub Desktop.
sfdx-lwc-jest utility for testing async functionality
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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