test(pdf-renderer): guard init() against repeated calls — libLoader must fire once

Adds idempotency test: calling init() twice must invoke libLoader only once.
Adds `if (pdfjsReady) return;` guard to satisfy the contract.

Addresses Felix Brandt round-4 suggestion on PR #536.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Marcel
2026-05-12 09:25:13 +02:00
parent 48b7e0f3a2
commit 0b3ce838f4
2 changed files with 14 additions and 0 deletions

View File

@@ -86,4 +86,17 @@ describe('createPdfRenderer', () => {
await expect(r.init()).rejects.toThrow('load failed');
expect(r.pdfjsReady).toBe(false);
});
it('init() is idempotent — libLoader called only once on repeated calls', async () => {
const fakePdfjs = {
GlobalWorkerOptions: { workerSrc: '' },
getDocument: vi.fn(),
TextLayer: class {}
} as unknown as typeof import('pdfjs-dist');
const fakeLoader = vi.fn().mockResolvedValue([fakePdfjs, { default: '' }] as const);
const r = createPdfRenderer(fakeLoader);
await r.init();
await r.init();
expect(fakeLoader).toHaveBeenCalledOnce();
});
});

View File

@@ -23,6 +23,7 @@ export function createPdfRenderer(libLoader: LibLoader = defaultLibLoader) {
let pdfjsLib: typeof import('pdfjs-dist') | null = null;
async function init(): Promise<void> {
if (pdfjsReady) return;
const [lib, { default: workerUrl }] = await libLoader();
lib.GlobalWorkerOptions.workerSrc = workerUrl;
pdfjsLib = lib;