0
0
mirror of https://github.com/wagtail/wagtail.git synced 2024-11-25 05:02:57 +01:00

Create shared util domReady

This commit is contained in:
LB Johnston 2023-02-19 14:11:45 +10:00 committed by Sage Abdullah
parent 0ba6cb726c
commit 4195f80d29
No known key found for this signature in database
GPG Key ID: EB1A33CC51CC0217
2 changed files with 52 additions and 0 deletions

View File

@ -0,0 +1,36 @@
import { domReady } from './domReady';
jest.useFakeTimers();
describe('domReady', () => {
it('should resolve as true if the DOM is not in loading state', () => {
expect(document.readyState).toEqual('complete');
return domReady().then(() => {
expect(document.readyState).toEqual('complete');
});
});
it('should resolve as true if the DOM loading but then completes loading', () => {
let trackingValue = null;
Object.defineProperty(document, 'readyState', {
value: 'loading',
});
expect(document.readyState).toEqual('loading');
setTimeout(() => {
trackingValue = true;
document.dispatchEvent(new CustomEvent('DOMContentLoaded'));
}, 5);
const promise = domReady();
jest.runAllTimers();
return promise.then(() => {
expect(trackingValue).toEqual(true);
});
});
});

View File

@ -0,0 +1,16 @@
/**
* Returns a promise that resolves once the DOM is ready for interaction.
*/
const domReady = async () =>
new Promise<void>((resolve) => {
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => resolve(), {
once: true,
passive: true,
});
} else {
resolve();
}
});
export { domReady };