Compare commits

..

18 Commits

Author SHA1 Message Date
Marcel
bc2dd3a98a fix(notification): add role=link and touch target to view-all button
Some checks failed
CI / Backend Unit Tests (push) Successful in 4m15s
CI / fail2ban Regex (push) Successful in 39s
CI / Compose Bucket Idempotency (push) Failing after 11s
CI / OCR Service Tests (pull_request) Successful in 17s
CI / Backend Unit Tests (pull_request) Successful in 4m17s
CI / Unit & Component Tests (push) Failing after 1m48s
CI / OCR Service Tests (push) Successful in 17s
CI / Unit & Component Tests (pull_request) Failing after 2m3s
CI / fail2ban Regex (pull_request) Successful in 40s
CI / Compose Bucket Idempotency (pull_request) Failing after 11s
- role="link" restores screen reader link semantics (Leonie blocker)
- min-h-[44px] px-1 meets WCAG 2.2 §2.5.8 and our 44×48px target size
- Comment in handleViewAll explains close-before-navigate ordering
- Tests updated to getByRole('link') + new call-order assertion

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 17:43:11 +02:00
Marcel
3005782a75 docs(adr-012): correct pattern note to document button+goto, not anchor+preventDefault
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 17:43:11 +02:00
Marcel
8ccc9aba1a fix(notification): replace view-all anchor with button to prevent iframe navigation
SvelteKit's capture-phase link interceptor fires before the component's
onclick handler, so e.preventDefault() was structurally too late to stop
iframe navigation in vitest-browser. Replacing the <a href> with a
<button type="button"> removes the href entirely — the interceptor never
fires — and the existing goto() mock in tests is sufficient.

Also splits the single view-all test into two focused it() blocks and
clears mocks in afterEach to prevent cross-test mock leakage.

Fixes #551

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 17:43:11 +02:00
Marcel
d21ba8fed2 refactor(pdf-viewer-tests): extract shared fake, add loadDocument error path, fix assertions
Some checks failed
CI / Unit & Component Tests (pull_request) Has been cancelled
CI / OCR Service Tests (pull_request) Has been cancelled
CI / Backend Unit Tests (pull_request) Has been cancelled
CI / fail2ban Regex (pull_request) Has been cancelled
CI / Compose Bucket Idempotency (pull_request) Has been cancelled
CI / Unit & Component Tests (push) Failing after 2m3s
CI / OCR Service Tests (push) Successful in 16s
CI / Backend Unit Tests (push) Successful in 4m15s
CI / fail2ban Regex (push) Successful in 38s
CI / Compose Bucket Idempotency (push) Failing after 11s
- Extract makeFakePdfjsLib / makeFakeLibLoader to testHelpers.ts — single
  source of truth used by both PdfViewer.svelte.test.ts and
  usePdfRenderer.svelte.test.ts; removes the diverging-fidelity DRY violation
  flagged by @felixbrandt and @saraholt in the PR review
- Add 'loadDocument sets error and loading=false when getDocument().promise
  rejects' test to usePdfRenderer.svelte.test.ts — closes the error-path gap
  flagged by @felixbrandt and @saraholt
- Replace toBeInTheDocument() with toBeVisible() in the three absorbed
  spec-file tests — uniform assertion style across the loaded-state describe
  block, as flagged by @felixbrandt

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 16:19:26 +02:00
Marcel
23cbb6be22 test(pdf-renderer): eliminate real pdfjs-dist loading from browser tests — use fake libLoader for all init() calls
Five tests in usePdfRenderer.svelte.test.ts called createPdfRenderer() without
a libLoader, causing init() to dynamically import pdfjs-dist in the browser.
Every dynamic import goes through Playwright's route handler, which calls
resolveManualMock via birpc to check for mocks. If the RPC closes during
teardown while one of these imports is in flight, the birpc race fires —
even though pdfjs-dist was never explicitly vi.mock()-ed.

Replace all bare createPdfRenderer() calls that invoke init() with
createPdfRenderer(makeFakeLibLoader()), identical to the pattern already
used in PdfViewer.svelte.test.ts. No real module loads, no route-handler
calls, no birpc exposure.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 16:19:26 +02:00
Marcel
9260866f47 ci(unit-tests): add early grep check for banned vi.mock pdfjs-dist pattern
Some checks failed
CI / Unit & Component Tests (push) Failing after 1m47s
CI / OCR Service Tests (push) Successful in 16s
CI / Backend Unit Tests (push) Successful in 4m11s
CI / fail2ban Regex (push) Successful in 38s
CI / Compose Bucket Idempotency (push) Failing after 11s
Adds a static grep step that runs after Lint and before the test suite.
Fails in ~1 s if any file under frontend/src/ contains the banned
vi.mock('pdfjs-dist' pattern, catching the regression before Playwright
spins up. Belt-and-suspenders with the ESLint rule (ADR 012).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 12:32:23 +02:00
Marcel
7c8811e439 refactor(eslint): ban vi.mock('pdfjs-dist', ...) in spec/test files — ADR 012
Adds a no-restricted-syntax rule scoped to *.spec.ts / *.test.ts that
flags any vi.mock call whose first argument starts with 'pdfjs-dist'.
Turns the ~2-min CI wait into an immediate lint error on save.
Updates ADR 012 Enforcement section to document the rule.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 12:32:23 +02:00
Marcel
ef592ddd0c test(pdf-viewer): consolidate spec.ts into test.ts — absorb page-counter test, delete spec
Absorbs the three tests from PdfViewer.svelte.spec.ts (nav buttons, zoom
controls, page counter) into the loaded-state describe in test.ts, then
deletes the now-empty spec file. One spec file per component.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 12:32:23 +02:00
Marcel
6c596babcb test(pdf-viewer): port PdfViewer.svelte.test.ts to libLoader prop injection — remove vi.mock
Removes both vi.mock('pdfjs-dist', …) calls that caused the birpc teardown
race (ADR 012). Replaces with static import + makeFakeLibLoader() helper
injected via the libLoader prop on every render() call.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 12:32:23 +02:00
Marcel
763e9f5708 docs(adr-012): add overlay navigation pattern note
Some checks failed
CI / Backend Unit Tests (push) Successful in 4m10s
CI / fail2ban Regex (push) Successful in 38s
CI / Compose Bucket Idempotency (push) Failing after 11s
CI / Unit & Component Tests (push) Failing after 1m50s
CI / OCR Service Tests (push) Successful in 16s
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 11:35:40 +02:00
Marcel
37026bbbb8 refactor(notification): extract handleViewAll named function
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 11:35:40 +02:00
Marcel
53ecfee25e test(notification): assert href is preserved on view-all link
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 11:35:40 +02:00
Marcel
fa4f8ed661 fix(style): move transkription print styles to global CSS to suppress Tailwind noise
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 11:35:40 +02:00
Marcel
890b811bc1 fix(style): move ChronikFuerDichBox animation to global CSS to suppress Tailwind noise
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 11:35:40 +02:00
Marcel
ed91c9bcf6 fix(notification): prevent iframe navigation — use goto instead of href follow
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 11:35:40 +02:00
Marcel
661e8582a2 test(notification): add goto mock and tighten selector in NotificationDropdown spec
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 11:35:40 +02:00
Marcel
7ee038faaf test(ocr): fix track_reactivity_loss in OcrTrainingCard spec
Some checks failed
CI / Unit & Component Tests (pull_request) Failing after 1m50s
CI / OCR Service Tests (pull_request) Successful in 16s
CI / Backend Unit Tests (pull_request) Successful in 4m11s
CI / fail2ban Regex (pull_request) Successful in 39s
CI / Compose Bucket Idempotency (pull_request) Failing after 11s
CI / Unit & Component Tests (push) Failing after 1m50s
CI / OCR Service Tests (push) Successful in 16s
CI / Backend Unit Tests (push) Successful in 4m7s
CI / fail2ban Regex (push) Successful in 37s
CI / Compose Bucket Idempotency (push) Failing after 10s
Two root causes:

1. In-flight test: resolveFetch() was the last line, leaving the async
   finally-block writing `training = false` after cleanup destroyed the
   component. Awaiting the button becoming re-enabled ensures the finally
   block settles before cleanup runs.

2. Success-dismiss test: startTraining() schedules setTimeout(5000) which
   fired after cleanup destroyed the component. vi.useFakeTimers() +
   vi.runAllTimers() scoped to the describe block drains the timer while
   the component is still alive.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 10:22:03 +02:00
Marcel
ae1688319e test(annotation): replace synchronous query().toBeNull() with async not.toBeInTheDocument()
Svelte defers DOM updates to microtasks; .query() is a synchronous
snapshot that can fire before the element disappears — making the
absence assertions in AnnotationShape and AnnotationLayer non-deterministic.

Sweeps all 4 instances across both spec files (Sara's ≤5 threshold).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 10:21:24 +02:00
10 changed files with 145 additions and 121 deletions

View File

@@ -36,6 +36,14 @@ jobs:
run: npm run lint
working-directory: frontend
- name: Assert no banned vi.mock patterns
shell: bash
run: |
if grep -rF "vi.mock('pdfjs-dist'" frontend/src/; then
echo "FAIL: banned vi.mock('pdfjs-dist') pattern found — see ADR 012. Use the libLoader prop injection pattern instead."
exit 1
fi
- name: Run unit and component tests with coverage
shell: bash
run: |

View File

@@ -88,5 +88,5 @@ These modules are resolved at static import time (before any test runs). Their `
- New browser-mode specs that need to stub an external library **must not** use `vi.mock(externalLib, factory)`. Add a loader/factory parameter to the underlying hook or service instead.
- The CI `unit-tests` job includes a permanent grep guard that fails the build if `rpc is closed` appears in any coverage run log. This catches regressions before they reach the acceptance criterion.
- Acceptance criterion for #535: 60 consecutive green `workflow_dispatch` CI runs against `main` after the fix is merged, with zero `rpc is closed` lines in any log.
- **Enforcement:** No automated lint rule is planned; the CI coverage guard is the regression backstop. If a lint rule is added later (e.g. an ESLint rule flagging `vi.mock` of non-virtual modules in browser-mode spec files), update this ADR.
- **Enforcement:** An ESLint `no-restricted-syntax` rule in `eslint.config.js` (scoped to `**/*.spec.ts` and `**/*.test.ts`) flags any `vi.mock('pdfjs-dist', ...)` call with a message referencing this ADR. This turns a ~2-minute CI wait into an immediate lint error on save. The CI birpc grep guard remains as belt-and-suspenders for the coverage run. A CI static grep step (added in issue #546) also catches the pattern before the test suite launches.
- **When to revisit the LibLoader home:** If three or more components adopt this pattern, consider extracting a shared `$lib/types/lib-loader.ts` or a generic `DynamicImportLoader<T>` type to avoid parallel type definitions across modules.

View File

@@ -72,6 +72,20 @@ export default defineConfig(
]
}
},
{
files: ['**/*.spec.ts', '**/*.test.ts'],
rules: {
'no-restricted-syntax': [
'error',
{
selector:
"CallExpression[callee.object.name='vi'][callee.property.name='mock'] > Literal[value=/^pdfjs-dist/]",
message:
"Banned: vi.mock('pdfjs-dist', factory) causes a birpc teardown race in browser-mode specs — see ADR 012. Use the libLoader prop injection pattern instead."
}
]
}
},
{
plugins: { boundaries },
settings: {

View File

@@ -107,7 +107,7 @@ describe('AnnotationLayer', () => {
});
await expect.element(page.getByTestId('annotation-ann-1')).toBeInTheDocument();
expect(page.getByTestId('annotation-delete-ann-1').query()).toBeNull();
await expect.element(page.getByTestId('annotation-delete-ann-1')).not.toBeInTheDocument();
});
it('does not show delete button when canDraw is false even if annotation is active', async () => {
@@ -120,6 +120,6 @@ describe('AnnotationLayer', () => {
});
await expect.element(page.getByTestId('annotation-ann-1')).toBeInTheDocument();
expect(page.getByTestId('annotation-delete-ann-1').query()).toBeNull();
await expect.element(page.getByTestId('annotation-delete-ann-1')).not.toBeInTheDocument();
});
});

View File

@@ -45,7 +45,7 @@ describe('AnnotationShape', () => {
onpointerleave: () => {}
});
expect(page.getByTestId('annotation-delete-ann-1').query()).toBeNull();
await expect.element(page.getByTestId('annotation-delete-ann-1')).not.toBeInTheDocument();
});
it('does not show delete button when showDelete is true but neither hovered nor active', async () => {
@@ -60,7 +60,7 @@ describe('AnnotationShape', () => {
onpointerleave: () => {}
});
expect(page.getByTestId('annotation-delete-ann-1').query()).toBeNull();
await expect.element(page.getByTestId('annotation-delete-ann-1')).not.toBeInTheDocument();
});
it('shows delete button when showDelete is true and isHovered is true', async () => {

View File

@@ -1,56 +0,0 @@
import { vi, describe, it, expect, afterEach } from 'vitest';
import { cleanup, render } from 'vitest-browser-svelte';
import { page } from 'vitest/browser';
import type { LibLoader } from '$lib/document/viewer/usePdfRenderer.svelte';
import PdfViewer from './PdfViewer.svelte';
afterEach(cleanup);
function makeFakePdfjsLib() {
class TextLayerMock {
render() {
return Promise.resolve();
}
cancel() {}
}
return {
GlobalWorkerOptions: { workerSrc: '' },
getDocument: vi.fn().mockReturnValue({
promise: Promise.resolve({
numPages: 2,
getPage: vi.fn().mockResolvedValue({
getViewport: vi.fn().mockReturnValue({ width: 595, height: 842 }),
render: vi.fn().mockReturnValue({ promise: Promise.resolve() }),
streamTextContent: vi.fn().mockReturnValue(new ReadableStream())
})
})
}),
TextLayer: TextLayerMock
} as unknown as typeof import('pdfjs-dist');
}
function makeFakeLibLoader(): LibLoader {
const fakePdfjs = makeFakePdfjsLib();
return vi.fn().mockResolvedValue([fakePdfjs, { default: '' }] as const);
}
describe('PdfViewer', () => {
it('shows previous and next page navigation buttons', async () => {
render(PdfViewer, { url: '/api/documents/test-id/file', libLoader: makeFakeLibLoader() });
await expect.element(page.getByRole('button', { name: /zurück/i })).toBeInTheDocument();
await expect.element(page.getByRole('button', { name: /weiter/i })).toBeInTheDocument();
});
it('shows zoom controls', async () => {
render(PdfViewer, { url: '/api/documents/test-id/file', libLoader: makeFakeLibLoader() });
await expect.element(page.getByRole('button', { name: /vergrößern/i })).toBeInTheDocument();
await expect.element(page.getByRole('button', { name: /verkleinern/i })).toBeInTheDocument();
});
it('displays the page counter once the PDF has loaded', async () => {
render(PdfViewer, { url: '/api/documents/test-id/file', libLoader: makeFakeLibLoader() });
// Fake loader resolves synchronously, so "1 / 2" should appear quickly
await expect.element(page.getByText(/1\s*\/\s*2/)).toBeInTheDocument();
});
});

View File

@@ -1,43 +1,20 @@
import { describe, it, expect, vi, afterEach } from 'vitest';
import { cleanup, render } from 'vitest-browser-svelte';
import { page } from 'vitest/browser';
vi.mock('pdfjs-dist', () => {
function TextLayerMock() {}
TextLayerMock.prototype.render = () => Promise.resolve();
TextLayerMock.prototype.cancel = () => {};
return {
GlobalWorkerOptions: { workerSrc: '' },
getDocument: vi.fn().mockReturnValue({
promise: Promise.resolve({
numPages: 2,
getPage: vi.fn().mockResolvedValue({
getViewport: vi.fn().mockReturnValue({ width: 595, height: 842 }),
render: vi.fn().mockReturnValue({ promise: Promise.resolve() }),
streamTextContent: vi.fn().mockReturnValue(new ReadableStream())
})
})
}),
TextLayer: TextLayerMock
};
});
vi.mock('pdfjs-dist/build/pdf.worker.min.mjs?url', () => ({ default: '' }));
const { default: PdfViewer } = await import('./PdfViewer.svelte');
import PdfViewer from './PdfViewer.svelte';
import { makeFakeLibLoader } from './testHelpers';
afterEach(cleanup);
describe('PdfViewer — empty / error states', () => {
it('renders the no-file placeholder when url is empty', async () => {
render(PdfViewer, { url: '' });
render(PdfViewer, { url: '', libLoader: makeFakeLibLoader() });
await expect.element(page.getByText('Keine Datei vorhanden')).toBeVisible();
});
it('does not render the controls when url is empty', async () => {
render(PdfViewer, { url: '' });
render(PdfViewer, { url: '', libLoader: makeFakeLibLoader() });
const buttons = document.querySelectorAll('button');
expect(buttons.length).toBe(0);
@@ -49,10 +26,10 @@ describe('PdfViewer — loaded state', () => {
render(PdfViewer, {
url: '/api/documents/test/file',
documentId: 'test',
annotationReloadKey: 0
annotationReloadKey: 0,
libLoader: makeFakeLibLoader()
});
// PdfControls renders its nav + zoom buttons once the document.promise resolves.
await expect.element(page.getByRole('button', { name: 'Zurück' })).toBeVisible();
await expect.element(page.getByRole('button', { name: 'Weiter' })).toBeVisible();
await expect.element(page.getByRole('button', { name: 'Vergrößern' })).toBeVisible();
@@ -63,7 +40,8 @@ describe('PdfViewer — loaded state', () => {
render(PdfViewer, {
url: '/api/documents/test/file',
documentId: 'test',
annotationsDimmed: true
annotationsDimmed: true,
libLoader: makeFakeLibLoader()
});
await vi.waitFor(() => {
@@ -96,11 +74,10 @@ describe('PdfViewer — loaded state', () => {
url: '/api/documents/test/file',
documentId: 'test',
transcribeMode: true,
documentFileHash: 'match'
documentFileHash: 'match',
libLoader: makeFakeLibLoader()
});
// transcribeMode forces showAnnotations=true; toggle button surfaces with "hide" label
// (only when annotationCount > 0).
await expect
.element(page.getByRole('button', { name: /annotierungen verbergen/i }))
.toBeVisible();
@@ -113,7 +90,8 @@ describe('PdfViewer — loaded state', () => {
render(PdfViewer, {
url: '/api/documents/test/file',
documentId: 'test',
documentFileHash: 'abc123'
documentFileHash: 'abc123',
libLoader: makeFakeLibLoader()
});
await vi.waitFor(() => {
@@ -125,7 +103,8 @@ describe('PdfViewer — loaded state', () => {
render(PdfViewer, {
url: '/api/documents/test/file',
documentId: 'test',
flashAnnotationId: 'ann-flashing'
flashAnnotationId: 'ann-flashing',
libLoader: makeFakeLibLoader()
});
await expect.element(page.getByRole('button', { name: 'Zurück' })).toBeVisible();
@@ -135,7 +114,8 @@ describe('PdfViewer — loaded state', () => {
render(PdfViewer, {
url: '/api/documents/test/file',
documentId: 'test',
blockNumbers: { 'ann-1': 1, 'ann-2': 2 }
blockNumbers: { 'ann-1': 1, 'ann-2': 2 },
libLoader: makeFakeLibLoader()
});
await expect.element(page.getByRole('button', { name: 'Zurück' })).toBeVisible();
@@ -145,7 +125,8 @@ describe('PdfViewer — loaded state', () => {
render(PdfViewer, {
url: '/api/documents/test/file',
documentId: 'test',
activeAnnotationId: 'ann-1'
activeAnnotationId: 'ann-1',
libLoader: makeFakeLibLoader()
});
await expect.element(page.getByRole('button', { name: 'Zurück' })).toBeVisible();
@@ -156,10 +137,10 @@ describe('PdfViewer — loaded state', () => {
url: '/api/documents/test/file',
documentId: 'test',
transcribeMode: true,
activeAnnotationId: 'ann-1'
activeAnnotationId: 'ann-1',
libLoader: makeFakeLibLoader()
});
// Without an annotations fetch, the visibility toggle is hidden — just assert the always-on nav.
await expect.element(page.getByRole('button', { name: 'Zurück' })).toBeVisible();
await expect.element(page.getByRole('button', { name: 'Weiter' })).toBeVisible();
});
@@ -169,7 +150,8 @@ describe('PdfViewer — loaded state', () => {
render(PdfViewer, {
url: '/api/documents/test/file',
documentId: 'test',
onAnnotationClick
onAnnotationClick,
libLoader: makeFakeLibLoader()
});
await expect.element(page.getByRole('button', { name: 'Zurück' })).toBeVisible();
@@ -199,7 +181,8 @@ describe('PdfViewer — loaded state', () => {
render(PdfViewer, {
url: '/api/documents/test/file',
documentId: 'test',
documentFileHash: 'new-hash'
documentFileHash: 'new-hash',
libLoader: makeFakeLibLoader()
});
await vi.waitFor(() => {
@@ -234,10 +217,10 @@ describe('PdfViewer — loaded state', () => {
render(PdfViewer, {
url: '/api/documents/test/file',
documentId: 'test',
documentFileHash: 'matching-hash'
documentFileHash: 'matching-hash',
libLoader: makeFakeLibLoader()
});
// Controls finish mounting, and the outdated notice stays absent.
await expect.element(page.getByRole('button', { name: 'Zurück' })).toBeVisible();
expect(document.querySelector('[data-testid="annotation-outdated-notice"]')).toBeNull();
} finally {
@@ -250,10 +233,10 @@ describe('PdfViewer — loaded state', () => {
try {
render(PdfViewer, {
url: '/api/documents/test/file',
documentId: 'test'
documentId: 'test',
libLoader: makeFakeLibLoader()
});
// PDF rendering does not depend on the annotations fetch — controls still appear.
await expect.element(page.getByRole('button', { name: 'Zurück' })).toBeVisible();
expect(document.querySelector('[data-testid="annotation-outdated-notice"]')).toBeNull();
} finally {
@@ -268,7 +251,8 @@ describe('PdfViewer — loaded state', () => {
try {
render(PdfViewer, {
url: '/api/documents/test/file',
documentId: 'test'
documentId: 'test',
libLoader: makeFakeLibLoader()
});
await expect.element(page.getByRole('button', { name: 'Zurück' })).toBeVisible();
@@ -277,4 +261,21 @@ describe('PdfViewer — loaded state', () => {
fetchSpy.mockRestore();
}
});
it('shows previous and next page navigation buttons', async () => {
render(PdfViewer, { url: '/api/documents/test-id/file', libLoader: makeFakeLibLoader() });
await expect.element(page.getByRole('button', { name: /zurück/i })).toBeVisible();
await expect.element(page.getByRole('button', { name: /weiter/i })).toBeVisible();
});
it('shows zoom controls', async () => {
render(PdfViewer, { url: '/api/documents/test-id/file', libLoader: makeFakeLibLoader() });
await expect.element(page.getByRole('button', { name: /vergrößern/i })).toBeVisible();
await expect.element(page.getByRole('button', { name: /verkleinern/i })).toBeVisible();
});
it('displays the page counter once the PDF has loaded', async () => {
render(PdfViewer, { url: '/api/documents/test-id/file', libLoader: makeFakeLibLoader() });
await expect.element(page.getByText(/1\s*\/\s*2/)).toBeVisible();
});
});

View File

@@ -0,0 +1,31 @@
import { vi } from 'vitest';
import type { LibLoader } from './usePdfRenderer.svelte';
export function makeFakePdfjsLib() {
class TextLayerMock {
render() {
return Promise.resolve();
}
cancel() {}
}
return {
GlobalWorkerOptions: { workerSrc: '' },
getDocument: vi.fn().mockReturnValue({
promise: Promise.resolve({
numPages: 2,
getPage: vi.fn().mockResolvedValue({
getViewport: vi.fn().mockReturnValue({ width: 595, height: 842 }),
render: vi.fn().mockReturnValue({ promise: Promise.resolve() }),
streamTextContent: vi.fn().mockReturnValue(new ReadableStream())
})
})
}),
TextLayer: TextLayerMock
} as unknown as typeof import('pdfjs-dist');
}
export function makeFakeLibLoader(): LibLoader {
const fakePdfjs = makeFakePdfjsLib();
return vi.fn().mockResolvedValue([fakePdfjs, { default: '' }] as const);
}

View File

@@ -1,5 +1,6 @@
import { describe, it, expect, vi } from 'vitest';
import { createPdfRenderer } from './usePdfRenderer.svelte';
import { makeFakeLibLoader } from './testHelpers';
// Note: init() and loadDocument() require pdfjsLib (browser module).
// These tests cover pure state logic only — bounds clamping and zoom limits.
@@ -122,39 +123,36 @@ describe('createPdfRenderer', () => {
expect(r.scale).toBe(before);
});
it('init() is callable and resolves without throwing in browser env', async () => {
const r = createPdfRenderer();
it('init() sets pdfjsReady to true when loader resolves', async () => {
const r = createPdfRenderer(makeFakeLibLoader());
await expect(r.init()).resolves.toBeUndefined();
// pdfjsReady is now true
expect(r.pdfjsReady).toBe(true);
});
it('after init, loadDocument with a bogus URL sets error', async () => {
const r = createPdfRenderer();
it('after init, loadDocument completes and loading returns to false', async () => {
const r = createPdfRenderer(makeFakeLibLoader());
await r.init();
await r.loadDocument('about:invalid-pdf');
// Either error is set or loading flips back to false — both are acceptable
await r.loadDocument('/some/path');
expect(r.loading).toBe(false);
});
it('renderCurrentPage is a no-op when canvasEl is null but pdfjsLib is initialized', async () => {
const r = createPdfRenderer();
const r = createPdfRenderer(makeFakeLibLoader());
await r.init();
// Without setElements, canvasEl is null — early return
await expect(r.renderCurrentPage()).resolves.toBeUndefined();
});
it('renderCurrentPage is a no-op when textLayerEl is null', async () => {
const r = createPdfRenderer();
const r = createPdfRenderer(makeFakeLibLoader());
await r.init();
// Set only canvas, leave textLayer unset is not directly testable;
// confirm calling without elements wired returns early.
// Without setElements, textLayerEl is null — early return
await expect(r.renderCurrentPage()).resolves.toBeUndefined();
});
it('init() can be called multiple times safely', async () => {
const r = createPdfRenderer();
const r = createPdfRenderer(makeFakeLibLoader());
await r.init();
await r.init();
expect(r.pdfjsReady).toBe(true);
@@ -206,4 +204,24 @@ describe('createPdfRenderer', () => {
await r.init();
expect(fakeLoader).toHaveBeenCalledOnce();
});
it('loadDocument sets error and loading=false when getDocument().promise rejects', async () => {
const failingLib = {
GlobalWorkerOptions: { workerSrc: '' },
getDocument: vi.fn().mockReturnValue({
promise: Promise.reject(new Error('PDF not found'))
}),
TextLayer: class {
render() {
return Promise.resolve();
}
cancel() {}
}
} as unknown as typeof import('pdfjs-dist');
const r = createPdfRenderer(vi.fn().mockResolvedValue([failingLib, { default: '' }] as const));
await r.init();
await r.loadDocument('/bad/path');
expect(r.loading).toBe(false);
expect(r.error).toBe('PDF not found');
});
});

View File

@@ -1,4 +1,4 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { cleanup, render } from 'vitest-browser-svelte';
import { page } from 'vitest/browser';
import OcrTrainingCard from './OcrTrainingCard.svelte';
@@ -74,6 +74,12 @@ describe('OcrTrainingCard — enabled state', () => {
});
describe('OcrTrainingCard — success dismiss button', () => {
beforeEach(() => vi.useFakeTimers());
afterEach(() => {
vi.runAllTimers();
vi.useRealTimers();
});
it('dismiss button has 44×44px touch target (h-11 w-11)', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true }));
@@ -108,7 +114,9 @@ describe('OcrTrainingCard — in-flight state', () => {
// While fetch is still pending the button label becomes "…"
await expect.element(page.getByRole('button', { name: '…' })).toBeInTheDocument();
// Cleanup: resolve the pending promise
resolveFetch({ ok: false });
await expect
.element(page.getByRole('button', { name: /Training starten/i }))
.not.toBeDisabled();
});
});