Files
faunosteo/apps/app/tests/unit/pdf.browserRasterizer.test.ts

82 lines
2.6 KiB
TypeScript

/**
* Replaces pdf.svgToPng.test.ts: the browser rasterizer adapter stamps the
* engine's size on the SVG root, draws through Image/canvas and returns PNG
* bytes, with the toDataURL fallback when toBlob yields nothing.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { browserRasterizer } from '@/pdf/browserRasterizer'
const PNG_BYTES = new Uint8Array([
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x00,
])
const SVG = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"/>'
const SIZE = { widthPx: 10, heightPx: 6 }
class MockImage {
decoding: 'sync' | 'async' | 'auto' = 'auto'
crossOrigin: string | null = null
onload: (() => void) | null = null
onerror: ((err?: unknown) => void) | null = null
private _src = ''
get src(): string {
return this._src
}
set src(value: string) {
this._src = value
queueMicrotask(() => this.onload?.())
}
}
const blobs: Blob[] = []
function mockCanvas(toBlob: (cb: BlobCallback) => void): HTMLCanvasElement {
const canvas = document.createElement('canvas')
canvas.getContext = (() => ({
fillStyle: '',
fillRect: () => undefined,
drawImage: () => undefined,
})) as unknown as HTMLCanvasElement['getContext']
canvas.toBlob = toBlob as HTMLCanvasElement['toBlob']
vi.spyOn(document, 'createElement').mockImplementation(((tag: string) =>
tag === 'canvas'
? canvas
: ({} as HTMLElement)) as typeof document.createElement)
return canvas
}
describe('browserRasterizer', () => {
beforeEach(() => {
blobs.length = 0
vi.stubGlobal('Image', MockImage)
vi.stubGlobal('URL', {
createObjectURL: (blob: Blob) => {
blobs.push(blob)
return 'blob:mock'
},
revokeObjectURL: () => undefined,
})
})
it('returns PNG bytes for a valid SVG, sized by the engine', async () => {
const canvas = mockCanvas((cb) =>
cb(new Blob([PNG_BYTES], { type: 'image/png' })),
)
const out = await browserRasterizer(SVG, SIZE)
expect(out).toBeInstanceOf(Uint8Array)
expect(Array.from(out.slice(0, 4))).toEqual([0x89, 0x50, 0x4e, 0x47])
expect([canvas.width, canvas.height]).toEqual([10, 6])
const served = await blobs[0]!.text()
expect(served).toContain('width="10"')
expect(served).toContain('height="6"')
})
it('falls back to toDataURL when toBlob returns null', async () => {
const canvas = mockCanvas((cb) => cb(null))
canvas.toDataURL = () =>
'data:image/png;base64,' + Buffer.from(PNG_BYTES).toString('base64')
const out = await browserRasterizer(SVG, SIZE)
expect(out[0]).toBe(0x89)
expect(out[1]).toBe(0x50)
})
})