Commit 3019860b authored by Jose Ivan Vargas's avatar Jose Ivan Vargas

Merge branch 'jnnkl-DomContent-Loaded-autosize' into 'master'

Remove obsolete DOMContentLoadedEventListener

See merge request gitlab-org/gitlab!52313
parents 2a03d152 fc9f53ab
import Autosize from 'autosize'; import Autosize from 'autosize';
import { waitForCSSLoaded } from '~/helpers/startup_css_helper'; import { waitForCSSLoaded } from '~/helpers/startup_css_helper';
document.addEventListener('DOMContentLoaded', () => { waitForCSSLoaded(() => {
waitForCSSLoaded(() => { const autosizeEls = document.querySelectorAll('.js-autosize');
const autosizeEls = document.querySelectorAll('.js-autosize');
Autosize(autosizeEls); Autosize(autosizeEls);
Autosize.update(autosizeEls); Autosize.update(autosizeEls);
autosizeEls.forEach((el) => el.classList.add('js-autosize-initialized')); autosizeEls.forEach((el) => el.classList.add('js-autosize-initialized'));
});
}); });
import '~/behaviors/autosize'; import '~/behaviors/autosize';
function load() {
document.dispatchEvent(new Event('DOMContentLoaded'));
}
jest.mock('~/helpers/startup_css_helper', () => { jest.mock('~/helpers/startup_css_helper', () => {
return { return {
waitForCSSLoaded: jest.fn().mockImplementation((cb) => cb.apply()), waitForCSSLoaded: jest.fn().mockImplementation((cb) => {
// This is a hack:
// autosize.js will execute and modify the DOM
// whenever waitForCSSLoaded calls its callback function.
// This setTimeout is here because everything within setTimeout will be queued
// as async code until the current call stack is executed.
// If we would not do this, the mock for waitForCSSLoaded would call its callback
// before the fixture in the beforeEach is set and the Test would fail.
// more on this here: https://johnresig.com/blog/how-javascript-timers-work/
setTimeout(() => {
cb.apply();
}, 0);
}),
}; };
}); });
...@@ -16,9 +24,15 @@ describe('Autosize behavior', () => { ...@@ -16,9 +24,15 @@ describe('Autosize behavior', () => {
}); });
it('is applied to the textarea', () => { it('is applied to the textarea', () => {
load(); // This is the second part of the Hack:
// Because we are forcing the mock for WaitForCSSLoaded and the very end of our callstack
const textarea = document.querySelector('textarea'); // to call its callback. This querySelector needs to go to the very end of our callstack
expect(textarea.classList).toContain('js-autosize-initialized'); // as well, if we would not have this setTimeout Function here, the querySelector
// would run before the mockImplementation called its callBack Function
// the DOM Manipulation didn't happen yet and the test would fail.
setTimeout(() => {
const textarea = document.querySelector('textarea');
expect(textarea.classList).toContain('js-autosize-initialized');
}, 0);
}); });
}); });
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment