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

feed.test.ts

51 lines1.9 KB

1import { test } from "node:test";
2import assert from "node:assert/strict";
3import { sortStories, parseFeedPage, type Story } from "../lib/types";
4import { articleLink, decodeTitle, userLink } from "../lib/links";
5import { itemRecord } from "../ingest/store";
6const row = (id: number, rank: number) => ({ item_id: id, rank }) as Story;
7test("ranks reorder stable IDs, including inserted rows, resets and page boundaries", () => {
8 const before = [row(1, 1), row(2, 2), row(3, 30)];
9 const after = [row(1, 31), row(2, 1), row(4, 2), row(3, 3)];
10 assert.deepEqual(
11 sortStories(after).map((r) => r.item_id),
12 [2, 4, 3, 1],
13 );
14 assert.deepEqual(
15 before.map((r) => r.item_id),
16 [1, 2, 3],
17 );
18 assert.deepEqual(
19 sortStories([row(5, 2), row(4, 2)]).map((r) => r.item_id),
20 [4, 5],
21 );
22});
23test("sealed feed inputs are bounded", () => {
24 assert.deepEqual(parseFeedPage("new", "5"), { feed: "new", page: 5 });
25 for (const input of ["0", "6", "1.0", "NaN", "-1", "1 OR 1=1"])
26 assert.throws(() => parseFeedPage("top", input));
27 assert.throws(() => parseFeedPage("anything", "1"));
28});
29test("HN titles render as text and outbound links use safe protocols", () => {
30 assert.equal(decodeTitle("A &amp; B &#x3C;script&#x3E;"), "A & B <script>");
31 assert.equal(
32 articleLink("javascript:alert(1)", 12),
33 "https://news.ycombinator.com/item?id=12",
34 );
35 assert.equal(
36 articleLink(null, 12),
37 "https://news.ycombinator.com/item?id=12",
38 );
39 assert.equal(userLink("a&b"), "https://news.ycombinator.com/user?id=a%26b");
40});
41test("null, removed, incomplete and job items have safe database representations", () => {
42 assert.equal(itemRecord({ id: 1, deleted: true }, "now").deleted, true);
43 assert.equal(
44 itemRecord({ id: 1, title: "gone", dead: true }, "now").dead,
45 true,
46 );
47 assert.equal(
48 itemRecord({ id: 2, type: "job", title: "Hiring" }, "now").score,
49 0,
50 );
51});