Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/test-e2e.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ concurrency:
jobs:
e2e:
if: ( github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name ) && ( github.actor != 'dependabot[bot]' )
runs-on: ubuntu-latest
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
- name: Setup Node
Expand Down
50 changes: 50 additions & 0 deletions assets/js/modules/__tests__/background.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ describe('optmlBackground', () => {

mockObserver = {
observe: jest.fn(),
unobserve: jest.fn(),
disconnect: jest.fn()
};

Expand All @@ -44,6 +45,44 @@ describe('optmlBackground', () => {
});

describe('setupBackgroundImageObservation', () => {
test('issue 1216: keeps watching pending elements after the first one is lazyloaded', () => {
let classCallback;
const classObserverInstance = { observe: jest.fn(), disconnect: jest.fn() };
global.MutationObserver = jest.fn((callback) => {
classCallback = callback;
return classObserverInstance;
});
document.body.innerHTML = '<div class="bg"></div><div class="bg"></div>';
const [first, second] = document.querySelectorAll('div');
optmlDomUtils.getUniqueSelector.mockReturnValue('div.bg');
optmlDomUtils.hasBackgroundImage.mockReturnValue(true);

optmlBackground.setupBackgroundImageObservation([first, second], '.bg', new Map(), mockObserver);

first.classList.add('optml-bg-lazyloaded');
classCallback([{ target: first }]);
expect(classObserverInstance.disconnect).not.toHaveBeenCalled();

second.classList.add('optml-bg-lazyloaded');
classCallback([{ target: second }]);
expect(mockObserver.observe).toHaveBeenCalledWith(first);
expect(mockObserver.observe).toHaveBeenCalledWith(second);
expect(classObserverInstance.disconnect).toHaveBeenCalledTimes(1);
});

test('issue 1216: re-observes a lazyloaded element so an already observed img gets a fresh callback', () => {
document.body.innerHTML = '<img data-opt-id="7" class="optml-bg-lazyloaded" />';
const img = document.querySelector('img');
optmlDomUtils.getUniqueSelector.mockReturnValue('img.bg');
optmlDomUtils.hasBackgroundImage.mockReturnValue(true);

optmlBackground.setupBackgroundImageObservation([img], '.bg', new Map(), mockObserver);

expect(mockObserver.unobserve).toHaveBeenCalledWith(img);
expect(mockObserver.observe).toHaveBeenCalledWith(img);
expect(mockObserver.unobserve.mock.invocationCallOrder[0]).toBeLessThan(mockObserver.observe.mock.invocationCallOrder[0]);
});

test('should setup observation for elements', () => {
document.body.innerHTML = `
<div class="bg-element"></div>
Expand Down Expand Up @@ -294,6 +333,17 @@ describe('optmlBackground', () => {
expect(result.selectorMap.get('.bg-element')).toEqual([]);
});

test('issue 1216: populates the provided selector map shared with the observer', () => {
document.body.innerHTML = '<div class="bg-element"></div>';
optmlDomUtils.getUniqueSelector.mockReturnValue('div.bg-element');
const observerSelectorMap = new Map();

const result = optmlBackground.processBackgroundSelectors(['.bg-element'], mockObserver, observerSelectorMap);

expect(result.selectorMap).toBe(observerSelectorMap);
expect(observerSelectorMap.get('.bg-element')).toEqual([]);
});

test('should log warning for selectors with no elements', () => {
const result = optmlBackground.processBackgroundSelectors(['.non-existent'], mockObserver);

Expand Down
87 changes: 60 additions & 27 deletions assets/js/modules/__tests__/dom-utils.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,20 @@ describe('optmlDomUtils', () => {
expect(selector).toContain('another-class');
});

test.each([
['only the lazyload class', 'optml-bg-lazyloaded'],
['a whitespace-only class attribute', ' '],
])('should return a valid selector for an element with %s', (_label, classAttribute) => {
document.body.innerHTML = '<section id="c"><div></div><div></div></section>';
const element = document.querySelectorAll('#c > div')[1];
element.setAttribute('class', classAttribute);

const selector = optmlDomUtils.getUniqueSelector(element);

expect(selector).toBe('#c > div:nth-of-type(2)');
expect(document.querySelector(selector)).toBe(element);
});

test('should handle element without classes', () => {
document.body.innerHTML = '<div></div>';
const element = document.querySelector('div');
Expand Down Expand Up @@ -293,12 +307,15 @@ describe('optmlDomUtils', () => {
describe('waitForPageLoad', () => {
test('should resolve immediately if page is already loaded', async () => {
Object.defineProperty(document, 'readyState', { writable: true, configurable: true, value: 'complete' });
jest.useFakeTimers();
const resolved = jest.fn();

const startTime = Date.now();
await optmlDomUtils.waitForPageLoad();
const endTime = Date.now();
optmlDomUtils.waitForPageLoad().then(resolved);

expect(endTime - startTime).toBeLessThan(10);
// Flushes pending promises without letting any time pass.
await jest.advanceTimersByTimeAsync(0);
expect(resolved).toHaveBeenCalled();
jest.useRealTimers();
});

test('should wait for load event if page not complete', async () => {
Expand Down Expand Up @@ -329,54 +346,70 @@ describe('optmlDomUtils', () => {
test('should fallback to setTimeout if requestIdleCallback not available', async () => {
const originalRequestIdleCallback = global.requestIdleCallback;
delete global.requestIdleCallback;
jest.useFakeTimers();
const resolved = jest.fn();

const startTime = Date.now();
await optmlDomUtils.waitForIdleTime();
const endTime = Date.now();
optmlDomUtils.waitForIdleTime().then(resolved);

await jest.advanceTimersByTimeAsync(199);
expect(resolved).not.toHaveBeenCalled();
await jest.advanceTimersByTimeAsync(1);
expect(resolved).toHaveBeenCalled();
jest.useRealTimers();

expect(endTime - startTime).toBeGreaterThanOrEqual(200);

// Restore
global.requestIdleCallback = originalRequestIdleCallback;
});
});

describe('waitForViewportImages', () => {
// Fake timers: wall-clock timing can fire a millisecond early on a busy machine.
beforeEach(() => {
jest.useFakeTimers();
});

afterEach(() => {
jest.useRealTimers();
});

test('should resolve after delay if page already loaded', async () => {
Object.defineProperty(document, 'readyState', { writable: true, configurable: true, value: 'complete' });
const resolved = jest.fn();

const startTime = Date.now();
await optmlDomUtils.waitForViewportImages(100);
const endTime = Date.now();
optmlDomUtils.waitForViewportImages(100).then(resolved);

expect(endTime - startTime).toBeGreaterThanOrEqual(100);
await jest.advanceTimersByTimeAsync(99);
expect(resolved).not.toHaveBeenCalled();
await jest.advanceTimersByTimeAsync(1);
expect(resolved).toHaveBeenCalled();
});

test('should wait for load event and then delay', async () => {
Object.defineProperty(document, 'readyState', { writable: true, configurable: true, value: 'loading' });
const resolved = jest.fn();

const promise = optmlDomUtils.waitForViewportImages(50);

// Simulate load event
setTimeout(() => {
window.dispatchEvent(new Event('load'));
}, 10);
optmlDomUtils.waitForViewportImages(50).then(resolved);

const startTime = Date.now();
await promise;
const endTime = Date.now();
await jest.advanceTimersByTimeAsync(1000);
expect(resolved).not.toHaveBeenCalled();

expect(endTime - startTime).toBeGreaterThanOrEqual(50);
window.dispatchEvent(new Event('load'));
await jest.advanceTimersByTimeAsync(49);
expect(resolved).not.toHaveBeenCalled();
await jest.advanceTimersByTimeAsync(1);
expect(resolved).toHaveBeenCalled();
});

test('should use default delay of 1000ms', async () => {
Object.defineProperty(document, 'readyState', { writable: true, configurable: true, value: 'complete' });
const resolved = jest.fn();

const startTime = Date.now();
await optmlDomUtils.waitForViewportImages();
const endTime = Date.now();
optmlDomUtils.waitForViewportImages().then(resolved);

expect(endTime - startTime).toBeGreaterThanOrEqual(1000);
await jest.advanceTimersByTimeAsync(999);
expect(resolved).not.toHaveBeenCalled();
await jest.advanceTimersByTimeAsync(1);
expect(resolved).toHaveBeenCalled();
});
});
});
Expand Down
67 changes: 67 additions & 0 deletions assets/js/modules/__tests__/image-detector.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,73 @@ describe('optmlImageDetector', () => {
// The observer is created successfully
expect(observer).toBeInstanceOf(IntersectionObserver);
});

test('issue 1216: records a background element under every watcher it matches', () => {
const selectorMap = new Map([
['[style*="background-image:url("]', []],
['[style*="background-image"][style*="url("]', []]
]);
document.body.innerHTML = '<div style="background-image:url(a.jpg)" data-optml-bg-selector="[style*=&quot;background-image&quot;][style*=&quot;url(&quot;]" data-optml-specific-selector="div.hero"></div>';

const observer = optmlImageDetector.createIntersectionObserver([], selectorMap);
observer.callback([{ isIntersecting: true, target: document.querySelector('div') }]);

expect(selectorMap.get('[style*="background-image:url("]')).toEqual(['div.hero']);
expect(selectorMap.get('[style*="background-image"][style*="url("]')).toEqual(['div.hero']);
});

test.each([
['with data-opt-id', ' data-opt-id="77"', [77]],
['without data-opt-id', '', []]
])('issue 1216: records an img background %s', (label, idAttribute, expectedImages) => {
const aboveTheFoldImages = [];
const selectorMap = new Map([['[style*="background-image:url("]', []]]);
document.body.innerHTML = `<img${idAttribute} style="background-image:url(a.jpg)" data-optml-bg-selector="x" data-optml-specific-selector="img.bg" />`;

const observer = optmlImageDetector.createIntersectionObserver(aboveTheFoldImages, selectorMap);
observer.callback([{ isIntersecting: true, target: document.querySelector('img') }]);

expect(selectorMap.get('[style*="background-image:url("]')).toEqual(['img.bg']);
expect(aboveTheFoldImages).toEqual(expectedImages);
});
});

describe('flushIntersectionObserver', () => {
test('records an element the observer has not reported before it is disconnected', async () => {
const aboveTheFoldImages = [];
const selectorMap = new Map([['[style*="background-image:url("]', []]]);
document.body.innerHTML = '<img data-opt-id="9" style="background-image:url(a.jpg)" data-optml-bg-selector="x" data-optml-specific-selector="img.late" />';
const observer = optmlImageDetector.createIntersectionObserver(aboveTheFoldImages, selectorMap);
observer.takeRecords = jest.fn(() => [{ isIntersecting: true, target: document.querySelector('img') }]);

await optmlImageDetector.flushIntersectionObserver(observer, aboveTheFoldImages, selectorMap);

expect(aboveTheFoldImages).toEqual([9]);
expect(selectorMap.get('[style*="background-image:url("]')).toEqual(['img.late']);
});

test('records queued entries when no frame is rendered, as in a hidden tab', async () => {
jest.useFakeTimers();
// Stubbed after the fake timers, which replace requestAnimationFrame too.
const requestAnimationFrameSpy = jest.spyOn(window, 'requestAnimationFrame').mockImplementation(() => 0);
try {
const aboveTheFoldImages = [];
const selectorMap = new Map([['[style*="background-image:url("]', []]]);
document.body.innerHTML = '<img data-opt-id="9" style="background-image:url(a.jpg)" data-optml-bg-selector="x" data-optml-specific-selector="img.late" />';
const observer = optmlImageDetector.createIntersectionObserver(aboveTheFoldImages, selectorMap);
observer.takeRecords = jest.fn(() => [{ isIntersecting: true, target: document.querySelector('img') }]);

const flushed = optmlImageDetector.flushIntersectionObserver(observer, aboveTheFoldImages, selectorMap);
await jest.advanceTimersByTimeAsync(100);
await flushed;

expect(aboveTheFoldImages).toEqual([9]);
expect(selectorMap.get('[style*="background-image:url("]')).toEqual(['img.late']);
} finally {
requestAnimationFrameSpy.mockRestore();
jest.useRealTimers();
}
});
});

Comment on lines +245 to 282

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tests The timeout branch of flushIntersectionObserver has no test. This case lets the jsdom requestAnimationFrame win the race. It still passes if setTimeout(resolve, 100) is removed. That branch keeps profiling from waiting until a hidden tab is shown again, since hidden tabs render no frames. Add a case in this describe. Call jest.useFakeTimers() first, then stub window.requestAnimationFrame with a function that never calls back. Fake timers replace requestAnimationFrame, so the stub must come after them. Run await jest.advanceTimersByTimeAsync(100), then expect the entry from takeRecords in aboveTheFoldImages and selectorMap. Restore real timers at the end.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. The new case records queued entries when no frame is rendered, as in a hidden tab stubs requestAnimationFrame after the fake timers and advances 100 ms. It passes at HEAD 1ad036a. With the setTimeout(resolve, 100) arm removed from flushIntersectionObserver, it fails with Exceeded timeout of 5000 ms for a test.

describe('observeOptimoleImages', () => {
Expand Down
Loading
Loading