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:
@@ -193,4 +193,17 @@ describe('createPdfRenderer', () => {
|
|||||||
await expect(r.init()).rejects.toThrow('load failed');
|
await expect(r.init()).rejects.toThrow('load failed');
|
||||||
expect(r.pdfjsReady).toBe(false);
|
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();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ export function createPdfRenderer(libLoader: LibLoader = defaultLibLoader) {
|
|||||||
let pdfjsLib: typeof import('pdfjs-dist') | null = null;
|
let pdfjsLib: typeof import('pdfjs-dist') | null = null;
|
||||||
|
|
||||||
async function init(): Promise<void> {
|
async function init(): Promise<void> {
|
||||||
|
if (pdfjsReady) return;
|
||||||
const [lib, { default: workerUrl }] = await libLoader();
|
const [lib, { default: workerUrl }] = await libLoader();
|
||||||
lib.GlobalWorkerOptions.workerSrc = workerUrl;
|
lib.GlobalWorkerOptions.workerSrc = workerUrl;
|
||||||
pdfjsLib = lib;
|
pdfjsLib = lib;
|
||||||
|
|||||||
Reference in New Issue
Block a user