refactor(shared): add BLOB_PRESENTER, unlock the blob-to-browser success paths (RB-28)

Three application-layer commands ended in raw DOM calls (URL.createObjectURL,
window.open, document.createElement('a').click(), URL.revokeObjectURL) as
their last statement. jsdom cannot assert a call that is also the end of the
function, so each command's success path stayed unassertable, and
StamdataStore.download()'s two-clause guard stayed permanently dark on its
true branch (TE-006).

Add BLOB_PRESENTER (libs/shared/src/application/blob-presenter.ts), an
InjectionToken mirroring SESSION_PORT's shape: an interface with open()/
download(), a real implementation preserving the existing open()-never-
revokes vs download()-always-revokes asymmetry, provided in root. Route
StamdataStore.download(), BriefStore.previewLetter(), and
OrgTemplateStore.proefbrief() through it.

Add specs with a recording fake presenter: StamdataStore.download()'s guard
(both clauses) and its success path, asserting toJson(...)'s exact output
reaches the file; BriefStore.previewLetter()'s existing success test now
goes through the seam instead of spying on window/URL directly; a new
org-template.store.spec.ts (none existed before) covers proefbrief()'s
success and failure paths.

Verified red without the fix by editing the download() filename to the
wrong extension, watching the success-path spec fail, then restoring it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
eho
2026-08-28 08:38:14 +02:00
co-authored by Claude Opus 5
parent e304211715
commit ce952941bb
10 changed files with 511 additions and 68 deletions
@@ -1,7 +1,8 @@
import { TestBed } from '@angular/core/testing';
import { describe, it, expect } from 'vitest';
import { Result, ok } from '@shared/kernel/fp';
import { StamRow, StamTable } from '@beheer/domain/stamdata';
import { BLOB_PRESENTER, BlobPresenter } from '@shared/application/blob-presenter';
import { StamRow, StamTable, toJson } from '@beheer/domain/stamdata';
import { StamdataAdapter } from '@beheer/infrastructure/stamdata.adapter';
import { StamdataStore } from './stamdata.store';
@@ -16,13 +17,30 @@ const table: StamTable = {
};
const rows: StamRow[] = [{ program: 'geneeskunde', beroep: 'Arts' }];
function setup(): StamdataStore {
/** A recording fake of BLOB_PRESENTER — records every call instead of touching the DOM,
which is what TE-006's seam is for: the store's success path becomes assertable. */
function fakeBlobPresenter() {
const opened: Blob[] = [];
const downloaded: { blob: Blob; filename: string }[] = [];
const presenter: BlobPresenter = {
open: (blob) => opened.push(blob),
download: (blob, filename) => downloaded.push({ blob, filename }),
};
return { presenter, opened, downloaded };
}
function setup(blobPresenter?: BlobPresenter): StamdataStore {
const adapter: Partial<StamdataAdapter> = {
list: (): Promise<Result<string, StamTable[]>> => Promise.resolve(ok([table])),
load: (): Promise<Result<string, { table: StamTable; rows: StamRow[] }>> =>
Promise.resolve(ok({ table, rows: rows.map((r) => ({ ...r })) })),
};
TestBed.configureTestingModule({ providers: [{ provide: StamdataAdapter, useValue: adapter }] });
TestBed.configureTestingModule({
providers: [
{ provide: StamdataAdapter, useValue: adapter },
...(blobPresenter ? [{ provide: BLOB_PRESENTER, useValue: blobPresenter }] : []),
],
});
return TestBed.inject(StamdataStore);
}
@@ -63,3 +81,57 @@ describe('StamdataStore undo/redo (WP-32)', () => {
expect(store.canUndo()).toBe(false);
});
});
// --- RB-28 (TE-006): download() ends in BLOB_PRESENTER.download, not raw DOM calls,
// so the seam makes both the guard's branches and the success path assertable. ---
describe('StamdataStore.download (RB-28)', () => {
it('does not call the presenter while the two-clause guard blocks (nothing dirty yet)', async () => {
// Given a freshly loaded table with no edits — canDownload() is false.
const { presenter, downloaded } = fakeBlobPresenter();
const store = setup(presenter);
await store.load();
expect(store.canDownload()).toBe(false);
// When download() is called...
store.download();
// Then the guard's true branch fires and the presenter is never reached.
expect(downloaded).toHaveLength(0);
});
it('does not call the presenter while previewing a date, even with edits', async () => {
// Given a loaded table with a real edit, but a preview date filter active.
const { presenter, downloaded } = fakeBlobPresenter();
const store = setup(presenter);
await store.load();
store.editCell(0, 'beroep', 'Chirurg');
store.setPreviewDate('2024-01-01');
expect(store.canDownload()).toBe(false);
// When download() is called...
store.download();
// Then the guard still blocks it.
expect(downloaded).toHaveLength(0);
});
it("passes toJson(...)'s exact output and the table id as the filename (success path)", async () => {
// Given a loaded table with a valid, dirty edit — canDownload() is true.
const { presenter, downloaded } = fakeBlobPresenter();
const store = setup(presenter);
await store.load();
store.editCell(0, 'beroep', 'Chirurg');
expect(store.canDownload()).toBe(true);
const expectedJson = toJson(store.table()!, store.rows());
// When download() is called...
store.download();
// Then the presenter receives exactly one call, with toJson's output reaching the
// file byte-for-byte and the table id as the file name.
expect(downloaded).toHaveLength(1);
expect(downloaded[0].filename).toBe('professions.json');
await expect(downloaded[0].blob.text()).resolves.toBe(expectedJson);
});
});
@@ -18,6 +18,7 @@ import {
reduce,
} from '@beheer/domain/stamdata-editor.machine';
import { StamdataAdapter } from '@beheer/infrastructure/stamdata.adapter';
import { BLOB_PRESENTER } from '@shared/application/blob-presenter';
type LoadedState = Extract<StamdataEditorState, { tag: 'loaded' }>;
@@ -30,6 +31,7 @@ type LoadedState = Extract<StamdataEditorState, { tag: 'loaded' }>;
@Injectable({ providedIn: 'root' })
export class StamdataStore {
private adapter = inject(StamdataAdapter);
private blobPresenter = inject(BLOB_PRESENTER);
private store = createStore<StamdataEditorState, StamdataEditorMsg>(initial, reduce);
readonly model = this.store.model;
@@ -138,12 +140,7 @@ export class StamdataStore {
const s = this.loaded();
if (!s || !this.canDownload()) return;
const blob = new Blob([toJson(s.table, s.rows)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${s.table.id}.json`;
a.click();
URL.revokeObjectURL(url);
this.blobPresenter.download(blob, `${s.table.id}.json`);
}
}
+13 -2
View File
@@ -20,7 +20,7 @@ tested where._
Every bullet below is a real test name from the suite — an `it()` title (frontend) or a test
method name (backend), read as a sentence. Nothing here is hand-written prose: this page
**is** the suite, reshaped for a business reader. 467 frontend behaviours across
**is** the suite, reshaped for a business reader. 472 frontend behaviours across
9 contexts; 261 backend behaviours across 42 test
classes.
@@ -114,6 +114,12 @@ classes.
- records addRow and undoes it
- clears history when switching table
#### StamdataStore.download (RB-28)
- does not call the presenter while the two-clause guard blocks (nothing dirty yet)
- does not call the presenter while previewing a date, even with edits
- passes toJson(...)'s exact output and the table id as the filename (success path)
#### activeOn (valid-time, half-open [van, tot))
- includes a row whose window covers the date
@@ -187,7 +193,7 @@ classes.
#### BriefStore.previewLetter
- opens the composed letter in a new tab on success
- opens the composed letter via BLOB_PRESENTER on success (RB-28)
- surfaces the error without opening a tab on failure
#### BriefStore.revealBigNummer (PRD-0002 §5c)
@@ -200,6 +206,11 @@ classes.
- sends no X-Role/X-Subject headers outside isDevMode()
- sends X-Role (and X-Subject when known) under isDevMode()
#### OrgTemplateStore.proefbrief (RB-28)
- opens the rendered proefbrief via BLOB_PRESENTER on success
- surfaces the error without opening a tab on failure
#### RevealBigNummerAdapter.reveal (BIO-006a + BIO-012)
- sends X-Step-Up only when the caller passes stepUp: true
@@ -0,0 +1,37 @@
import { InjectionToken } from '@angular/core';
/**
* A shared seam for handing a generated `Blob` to the browser, WITHOUT the calling
* command inlining `URL.createObjectURL`/`window.open`/`document.createElement('a')`
* as its own last statement (TE-006) — those calls are unassertable in jsdom because
* they are the end of the command, not a value the spec can intercept. A recording
* fake satisfies this shape in specs; `realBlobPresenter` is the production default.
*/
export interface BlobPresenter {
/** Open a blob in a new tab (e.g. a rendered letter preview). Never revokes the
object URL — the tab outlives this call, and the POC treats the leak as cheap
(see `BriefStore.previewLetter`'s original comment). */
open(blob: Blob): void;
/** Trigger a browser download of a blob under the given file name, then revoke the
object URL once the click has been dispatched. */
download(blob: Blob, filename: string): void;
}
const realBlobPresenter: BlobPresenter = {
open(blob: Blob) {
window.open(URL.createObjectURL(blob), '_blank');
},
download(blob: Blob, filename: string) {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
},
};
export const BLOB_PRESENTER = new InjectionToken<BlobPresenter>('BLOB_PRESENTER', {
providedIn: 'root',
factory: () => realBlobPresenter,
});