Skip to content
Source
Sign inSign up
samwillis/hackernews-realtime
Open History to see the last commit

events.test.ts

90 lines2.5 KB

1import { test } from "node:test";
2import assert from "node:assert/strict";
3import {
4 eventBuckets,
5 eventDescription,
6 inViewport,
7 TIMELINE_MS,
8 type HnEvent,
9} from "../lib/events";
10const event = (id: number, occurred_at: number): HnEvent => ({
11 event_id: id,
12 item_id: id,
13 story_id: id,
14 kind: "story-updated",
15 label: "Story",
16 details: '{"score":{"from":"1","to":"2"},"comments":{"from":"0","to":"1"}}',
17 occurred_at,
18});
19test("timeline keeps every event in busy bursts, independent of item or kind", () => {
20 const now = 180000;
21 const events = Array.from({ length: 1500 }, (_, i) => ({
22 ...event(i, now - 1000),
23 kind: i % 2 ? "comment-removed" : "new-left",
24 }));
25 const buckets = eventBuckets(
26 [
27 ...events,
28 event(1501, now - TIMELINE_MS),
29 event(1502, now - TIMELINE_MS - 1),
30 event(1503, now + 1),
31 ],
32 now,
33 );
34 assert.equal(buckets.flatMap((bucket) => bucket.events).length, 1501);
35 assert.equal(buckets[1].events.length, 1500);
36 assert.equal(buckets[0].events[0].event_id, 1501);
37 assert.equal(eventBuckets(events, now + TIMELINE_MS).length, 0);
38 const boundaryEvents = [
39 event(1, now - 60_001),
40 event(2, now - 60_000),
41 event(3, now - 1),
42 ];
43 assert.deepEqual(
44 eventBuckets(boundaryEvents, now, 60_000).flatMap((bucket) =>
45 bucket.events.map((row) => row.event_id),
46 ),
47 [2, 3],
48 );
49 assert.equal(
50 eventBuckets(boundaryEvents, now).flatMap((bucket) => bucket.events).length,
51 3,
52 );
53});
54test("visibility uses the unobscured viewport and includes partially visible rows", () => {
55 assert.equal(
56 inViewport({ top: 500, bottom: 650, left: 0, right: 600 }, 600, 550),
57 true,
58 );
59 assert.equal(
60 inViewport({ top: 550, bottom: 650, left: 0, right: 600 }, 600, 550),
61 false,
62 );
63 assert.equal(
64 inViewport({ top: -100, bottom: 1, left: 0, right: 600 }, 600, 550),
65 true,
66 );
67 assert.equal(
68 inViewport({ top: -100, bottom: 0, left: 0, right: 600 }, 600, 550),
69 false,
70 );
71});
72test("event details retain every changed field and tolerate malformed payloads", () => {
73 assert.equal(
74 eventDescription(event(1, 0)),
75 "story updated · score: 1 → 2 · comment count: 0 → 1",
76 );
77 assert.equal(
78 eventDescription({ ...event(1, 0), details: "oops" }),
79 "story updated",
80 );
81 assert.equal(
82 eventDescription({
83 ...event(1, 0),
84 kind: "comment-updated",
85 details:
86 '{"text":{"from":"<p>A &amp; B</p>","to":"<p>Updated <i>reply</i></p>"}}',
87 }),
88 "comment updated · text: A & B → Updated reply",
89 );
90});