tests/srt.test.cjs (2510 bytes)
1 /* node --test tests */ 2 const test = require('node:test'); 3 const assert = require('node:assert/strict'); 4 const { parse, cueAt, subtitleTime, seconds } = require('../src/srt.js'); 5 6 test('an .srt is read: numbers, stamps, text of more than one line, tags removed', () => { 7 const cues = parse('1\r\n00:00:01,500 --> 00:00:04,000\r\nIt was a <i>dark</i> night;\r\nthe rain fell.\r\n\r\n' + 8 '2\r\n01:02:03,004 --> 01:02:05,000\r\n吾輩は猫である。\r\n'); 9 assert.deepEqual(cues, [ 10 { start: 1.5, end: 4, text: 'It was a dark night;\nthe rain fell.' }, 11 { start: 3723.004, end: 3725, text: '吾輩は猫である。' }, 12 ]); 13 }); 14 15 test('a .vtt is read too, and what is not a cue is passed over', () => { 16 const cues = parse('WEBVTT\n\nNOTE made by hand\n\n00:01.000 --> 00:02.5\nHello\n\nbroken --> block\nx\n\n3\n00:00:09,000 --> 00:00:08,000\nends before it starts\n'); 17 assert.deepEqual(cues, [{ start: 1, end: 2.5, text: 'Hello' }]); 18 }); 19 20 test('stamps', () => { 21 assert.equal(seconds('00:00:00,004'), 0.004); 22 assert.equal(seconds('10:00:00.5'), 36000.5); 23 assert.ok(Number.isNaN(seconds('soon'))); 24 }); 25 26 test('the cue for a moment is the one a slow search finds, for any cues and any moment', () => { 27 let seed = 11; 28 const random = () => (seed = (seed * 1103515245 + 12345) >>> 0) / 2 ** 32; 29 for (let round = 0; round < 300; round++) { 30 const cues = []; 31 let t = random() * 5; 32 for (let i = 0; i < Math.floor(random() * 40); i++) { 33 const start = t, end = start + 0.2 + random() * 5; 34 cues.push({ start, end, text: String(i) }); 35 t = end + (random() < 0.5 ? 0 : random() * 3); // back to back, or a gap 36 } 37 for (let k = 0; k < 60; k++) { 38 const at = random() * (t + 5) - 1; 39 const slow = cues.filter((c) => c.start <= at && at < c.end).pop() ?? null; 40 assert.equal(cueAt(cues, at), slow); 41 } 42 } 43 assert.equal(cueAt([], 3), null); 44 }); 45 46 test('a cue that overlaps the one after it gives way to the later one', () => { 47 const cues = [{ start: 0, end: 10, text: 'long' }, { start: 4, end: 6, text: 'short' }]; 48 assert.equal(cueAt(cues, 5).text, 'short'); 49 assert.equal(cueAt(cues, 8).text, 'long'); 50 }); 51 52 test('the time of the video is moved onto the clock of the subtitles', () => { 53 assert.equal(subtitleTime(100, 0, 1), 100); 54 assert.equal(subtitleTime(100, 12.5, 1), 87.5); // the upload has a 12.5 s intro 55 assert.ok(Math.abs(subtitleTime(3600, 0, 1.001) - 3603.6) < 1e-9); // and runs a little slow 56 });