Files
pdf-tools/src/merge/mergeQueueHelpers.test.ts
2026-05-23 15:02:40 +02:00

83 lines
2.5 KiB
TypeScript

import { describe, expect, it } from 'vitest';
import type { MergeQueueItem } from './mergeTypes';
import {
canMergeQueue,
clampMergeInsertAt,
createMergedPdfName,
getReadyMergeQueuePdfs,
moveMergeQueueItem,
} from './mergeQueueHelpers';
function makeItem(
id: string,
status: MergeQueueItem['status']
): MergeQueueItem {
return {
id,
file: new File(['x'], `${id}.pdf`, { type: 'application/pdf' }),
name: `${id}.pdf`,
size: 1,
pageCount: status === 'ready' ? 1 : null,
pdf:
status === 'ready'
? {
id: `pdf-${id}`,
name: `${id}.pdf`,
// The helper tests never dereference the PDFDocument.
doc: {} as never,
pageCount: 1,
arrayBuffer: new ArrayBuffer(0),
}
: null,
status,
};
}
describe('merge queue helpers', () => {
it('moves queued items up and down without mutating the original array', () => {
const items = [
makeItem('a', 'ready'),
makeItem('b', 'ready'),
makeItem('c', 'ready'),
];
expect(moveMergeQueueItem(items, 'b', 'up').map((item) => item.id)).toEqual(
['b', 'a', 'c']
);
expect(
moveMergeQueueItem(items, 'b', 'down').map((item) => item.id)
).toEqual(['a', 'c', 'b']);
expect(items.map((item) => item.id)).toEqual(['a', 'b', 'c']);
});
it('only allows merging when every queued item is ready', () => {
const readyItems = [makeItem('a', 'ready'), makeItem('b', 'ready')];
const mixedItems = [makeItem('a', 'ready'), makeItem('b', 'loading')];
expect(canMergeQueue(readyItems)).toBe(true);
expect(getReadyMergeQueuePdfs(readyItems)).toHaveLength(2);
expect(canMergeQueue(mixedItems)).toBe(false);
expect(canMergeQueue([])).toBe(false);
});
it('clamps one-based merge positions to zero-based insert slots', () => {
expect(clampMergeInsertAt('1', 10)).toBe(0);
expect(clampMergeInsertAt('5', 10)).toBe(4);
expect(clampMergeInsertAt('99', 10)).toBe(10);
expect(clampMergeInsertAt('-10', 10)).toBe(0);
expect(clampMergeInsertAt('not-a-number', 10)).toBe(10);
});
it('creates readable merged PDF filenames', () => {
expect(createMergedPdfName('base.pdf', ['a.pdf', 'b.pdf'], 'append')).toBe(
'base_plus_2_pdfs.pdf'
);
expect(createMergedPdfName('base.pdf', ['a.pdf'], 'overwrite')).toBe(
'a_merged.pdf'
);
expect(createMergedPdfName(null, ['a.pdf', 'b.pdf'], 'overwrite')).toBe(
'merged_2_pdfs.pdf'
);
});
});