import { JSDOM } from 'jsdom'; import { collectAmazonCurrentPage, collectAmazonNextPageUrl, } from '../src/page-worker/web-injectors/amazon-search-pagination'; const withDom = async (url: string, html: string, callback: () => T | Promise) => { const dom = new JSDOM(html, { url }); const previousDocument = globalThis.document; const previousWindow = globalThis.window; Object.assign(globalThis, { document: dom.window.document, window: dom.window }); try { return await callback(); } finally { Object.assign(globalThis, { document: previousDocument, window: previousWindow }); dom.window.close(); } }; const testNextPage = async (name: string, html: string, expected: string | null) => { const actual = await withDom( 'https://www.amazon.com/s?k=security+camera&page=1', html, collectAmazonNextPageUrl, ); if (actual !== expected) throw new Error(`${name}: expected ${expected}, received ${actual}`); }; const testCurrentPage = async (name: string, url: string, html: string, expected: number) => { const actual = await withDom(url, html, collectAmazonCurrentPage); if (actual !== expected) throw new Error(`${name}: expected ${expected}, received ${actual}`); }; const main = async () => { await testNextPage( 'active next page', 'Next', 'https://www.amazon.com/s?k=security+camera&page=2', ); await testNextPage( 'disabled next page', 'Next', null, ); await testNextPage('missing next page', '
No pagination
', null); await testCurrentPage( 'visible page wins over hidden stale pagination selection', 'https://www.amazon.com/s?k=home+security&page=11&ref=sr_pg_11', '
12
11', 11, ); for (const page of [1, 2, 5, 10, 20]) { await testCurrentPage( `URL page ${page}`, `https://www.amazon.com/s?k=home+security&page=${page}&ref=sr_pg_${page}`, `${page}`, page, ); } await testCurrentPage( 'visible page wins while URL has advanced', 'https://www.amazon.com/s?k=home+security&page=3&ref=sr_pg_3', '2', 2, ); await testCurrentPage( 'invalid URL page uses ref fallback', 'https://www.amazon.com/s?k=home+security&page=invalid&ref=sr_pg_9', '
No selected pagination item
', 9, ); await testCurrentPage( 'ref page fallback', 'https://www.amazon.com/s?k=home+security&ref=sr_pg_7', '
No selected pagination item
', 7, ); await testCurrentPage( 'selected pagination fallback', 'https://www.amazon.com/s?k=home+security', '5', 5, ); await testCurrentPage( 'first page fallback', 'https://www.amazon.com/s?k=home+security', '
No pagination
', 1, ); console.log('Amazon search pagination tests passed.'); }; void main();