Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

refactor(ts): type the backend tests and fixtures

spacesdrivefc5fff7ecf4e
diff --git a/backend/tests/fixtures/fakeFetch.ts b/backend/tests/fixtures/fakeFetch.ts
index dd703dd..104d97c 100644
--- a/backend/tests/fixtures/fakeFetch.ts
+++ b/backend/tests/fixtures/fakeFetch.ts
@@ -1,14 +1,34 @@
+export interface RecordedRequest {
+ url: string;
+ method: string;
+ headers?: RequestInit['headers'];
+ body?: string;
+}
+
+export interface FakeReply {
+ body: unknown;
+ status: number;
+ statusText: string;
+}
+
+export type Responder = (request: RecordedRequest, count: number) => FakeReply | Error | Promise<FakeReply | Error>;
+
+export interface FetchMock {
+ requests: RecordedRequest[];
+ restore(): void;
+}
+
// replaces global fetch with a scripted responder and records each request
-export function reply(body, status = 200, statusText = 'OK') {
+export function reply(body: unknown, status = 200, statusText = 'OK'): FakeReply {
return { body, status, statusText };
}
-export function installFetch(respond) {
- const requests = [];
+export function installFetch(respond: Responder): FetchMock {
+ const requests: RecordedRequest[] = [];
const originalFetch = globalThis.fetch;
- globalThis.fetch = async (url, options = {}) => {
- const request = { url: String(url), method: options.method ?? 'GET' };
+ globalThis.fetch = async (url: unknown, options: RequestInit = {}): Promise<Response> => {
+ const request: RecordedRequest = { url: String(url), method: options.method ?? 'GET' };
if (options.headers) request.headers = options.headers;
if (options.body !== undefined) request.body = String(options.body);
requests.push(request);
@@ -20,7 +40,7 @@ export function installFetch(respond) {
statusText: outcome.statusText,
ok: outcome.status >= 200 && outcome.status < 300,
json: async () => outcome.body,
- };
+ } as unknown as Response;
};
return {
diff --git a/backend/tests/fixtures/fakeSupabase.ts b/backend/tests/fixtures/fakeSupabase.ts
index c7b622f..7df3301 100644
--- a/backend/tests/fixtures/fakeSupabase.ts
+++ b/backend/tests/fixtures/fakeSupabase.ts
@@ -1,31 +1,65 @@
// in-memory stand-in for the supabase query builder calls made by lib/db.js; records every call
-function copy(value) {
- return value === undefined ? undefined : structuredClone(value);
+import type { SupabaseClient } from '../../types/app.ts';
+
+export type Row = Record<string, unknown>;
+
+type Filter = [column: string, value: unknown, operator?: 'lte'];
+
+interface Action {
+ type: 'select' | 'update' | 'insert' | 'delete';
+ table: string;
+ columns?: string;
+ values?: Row;
}
-function matchesFilter(row, [column, value, operator]) {
- if (operator === 'lte') return row[column] <= value;
+export type SupabaseCall = Action & { filters: Filter[] };
+
+interface QueryResult {
+ data: unknown;
+ error: { message: string } | null;
+}
+
+interface FakeQuery {
+ select(): FakeQuery;
+ eq(column: string, value: unknown): FakeQuery;
+ lte(column: string, value: unknown): FakeQuery;
+ order(): FakeQuery;
+ single(): Promise<QueryResult>;
+ then(resolve: (result: QueryResult) => unknown, reject?: (reason: unknown) => unknown): Promise<unknown>;
+}
+
+type Run = (action: Action, filters: Filter[]) => Row[];
+
+// passed straight to code that expects a supabase client; calls and table expose what the fake recorded
+export type FakeSupabase = SupabaseClient & { calls: SupabaseCall[]; table: Row[] };
+
+function copy<T>(value: T): T {
+ return value === undefined ? undefined as T : structuredClone(value);
+}
+
+function matchesFilter(row: Row, [column, value, operator]: Filter) {
+ if (operator === 'lte') return (row[column] as string) <= (value as string);
return row[column] === value;
}
-function matchesFilters(row, filters) {
+function matchesFilters(row: Row, filters: Filter[]) {
return filters.every(filter => matchesFilter(row, filter));
}
// rows without a _table tag are visible to every table, as the older tests expect
-function inTable(row, name) {
+function inTable(row: Row, name: string) {
return row._table === undefined || row._table === name;
}
-function queryBuilder(action, run) {
- const filters = [];
- const query = {
+function queryBuilder(action: Action, run: Run): FakeQuery {
+ const filters: Filter[] = [];
+ const query: FakeQuery = {
select() { return query; },
- eq(column, value) {
+ eq(column: string, value: unknown) {
filters.push([column, value]);
return query;
},
- lte(column, value) {
+ lte(column: string, value: unknown) {
filters.push([column, value, 'lte']);
return query;
},
@@ -35,22 +69,22 @@ function queryBuilder(action, run) {
if (found.length === 0) return Promise.resolve({ data: null, error: { message: 'no rows' } });
return Promise.resolve({ data: found[0], error: null });
},
- then(resolve, reject) {
+ then(resolve: (result: QueryResult) => unknown, reject?: (reason: unknown) => unknown) {
return Promise.resolve({ data: run(action, filters), error: null }).then(resolve, reject);
},
};
return query;
}
-export function fakeSupabase(rows = []) {
+export function fakeSupabase(rows: Row[] = []): FakeSupabase {
const table = rows.map(copy);
- const calls = [];
+ const calls: SupabaseCall[] = [];
- function run(action, filters) {
+ function run(action: Action, filters: Filter[]) {
calls.push({ ...copy(action), filters: copy(filters) });
const found = table.filter(row => inTable(row, action.table) && matchesFilters(row, filters));
if (action.type === 'update') found.forEach(row => Object.assign(row, copy(action.values)));
- if (action.type === 'insert') table.push(copy(action.values));
+ if (action.type === 'insert') table.push(copy(action.values!));
if (action.type === 'delete') {
found.forEach(row => table.splice(table.indexOf(row), 1));
}
@@ -60,22 +94,22 @@ export function fakeSupabase(rows = []) {
return {
calls,
table,
- from(name) {
+ from(name: string) {
return {
- select: (columns) => queryBuilder({ type: 'select', table: name, columns }, run),
- update: (values) => queryBuilder({ type: 'update', table: name, values }, run),
- insert: (values) => queryBuilder({ type: 'insert', table: name, values }, run),
+ select: (columns: string) => queryBuilder({ type: 'select', table: name, columns }, run),
+ update: (values: Row) => queryBuilder({ type: 'update', table: name, values }, run),
+ insert: (values: Row) => queryBuilder({ type: 'insert', table: name, values }, run),
delete: () => queryBuilder({ type: 'delete', table: name }, run),
};
},
- };
+ } as unknown as FakeSupabase;
}
-export function tableRow(name, row) {
+export function tableRow(name: string, row: Row): Row {
return { _table: name, ...row };
}
-export function accountRow(account, userId = 'user-1') {
+export function accountRow(account: Row & { id: string; platform: string }, userId = 'user-1'): Row {
const { id, platform, ...data } = account;
return { id, platform, user_id: userId, data };
}
diff --git a/backend/tests/fixtures/golden.ts b/backend/tests/fixtures/golden.ts
index f04b526..fe5558b 100644
--- a/backend/tests/fixtures/golden.ts
+++ b/backend/tests/fixtures/golden.ts
@@ -2,22 +2,22 @@ import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
// json drops undefined and non-finite numbers, so mark them to keep them visible in the snapshot
-function encodeValue(_key, value) {
+function encodeValue(_key: string, value: unknown): unknown {
if (value === undefined) return '[undefined]';
if (typeof value === 'number' && !Number.isFinite(value)) return `[${value}]`;
return value;
}
-export function snapshot(value) {
+export function snapshot(value: unknown): unknown {
return JSON.parse(JSON.stringify(value, encodeValue));
}
-export function readGolden(name) {
+export function readGolden(name: string): unknown {
return JSON.parse(readFileSync(new URL(`./${name}.golden.json`, import.meta.url), 'utf8'));
}
// the string comparison also pins key order, which deepStrictEqual ignores
-export function assertGolden(actual, name) {
+export function assertGolden(actual: unknown, name: string): void {
const expected = readGolden(name);
const actualSnapshot = snapshot(actual);
assert.deepStrictEqual(actualSnapshot, expected);
diff --git a/backend/tests/fixtures/instagramFixtures.ts b/backend/tests/fixtures/instagramFixtures.ts
index 1145e58..dc6a22b 100644
--- a/backend/tests/fixtures/instagramFixtures.ts
+++ b/backend/tests/fixtures/instagramFixtures.ts
@@ -1,6 +1,9 @@
+import type { InstagramMedia } from '../../../shared/types/instagram.ts';
+
export const FIXED_NOW = Date.parse('2026-09-01T12:00:00Z');
-function mediaItem(id, contentType, timestamp, counts, caption = '') {
+// 'story' is not a known content type, so contentType is any string here
+function mediaItem(id: string, contentType: string, timestamp: string, counts: [number, number, number | null], caption = ''): InstagramMedia {
const [likeCount, commentsCount, viewCount] = counts;
return {
id,
@@ -14,7 +17,7 @@ function mediaItem(id, contentType, timestamp, counts, caption = '') {
likeCount,
commentsCount,
viewCount,
- };
+ } as InstagramMedia;
}
const longCaption = `${'Behind the scenes of the shoot. '.repeat(6)}#Café #travel #reels`;
@@ -41,8 +44,8 @@ export const zeroEngagementMedia = [
mediaItem('z3', 'reel', '2026-08-03T10:00:00+0000', [0, 0, 0]),
];
-function generatedCaption(index) {
- const tags = [];
+function generatedCaption(index: number) {
+ const tags: string[] = [];
for (let tag = 0; tag < 25; tag++) {
if ((tag + index) % 3 === 0) tags.push(`#tag${tag}`);
}
diff --git a/backend/tests/fixtures/redditFixtures.ts b/backend/tests/fixtures/redditFixtures.ts
index 3b6ae31..cf285fe 100644
--- a/backend/tests/fixtures/redditFixtures.ts
+++ b/backend/tests/fixtures/redditFixtures.ts
@@ -1,8 +1,16 @@
+import type { RedditPost } from '../../../shared/types/reddit.ts';
+
+// mediaType is any string and awardsCount is left out when the counts tuple has no fourth entry
+interface RedditPostFixture extends Omit<RedditPost, 'mediaType' | 'awardsCount'> {
+ mediaType: string;
+ awardsCount?: number;
+}
+
export const FIXED_NOW = Date.parse('2026-09-01T12:00:00Z');
-function redditPost(id, subreddit, createdAt, counts, mediaType = 'text') {
+function redditPost(id: string, subreddit: string, createdAt: string, counts: [number, number, number, number?], mediaType = 'text'): RedditPost {
const [score, numComments, upvoteRatio, awardsCount] = counts;
- const post = {
+ const post: RedditPostFixture = {
id,
title: `Post ${id}`,
subreddit,
@@ -21,7 +29,7 @@ function redditPost(id, subreddit, createdAt, counts, mediaType = 'text') {
flair: '',
};
if (awardsCount !== undefined) post.awardsCount = awardsCount;
- return post;
+ return post as RedditPost;
}
export const richPosts = [
diff --git a/backend/tests/fixtures/routeHarness.ts b/backend/tests/fixtures/routeHarness.ts
index d80aec6..a774d7c 100644
--- a/backend/tests/fixtures/routeHarness.ts
+++ b/backend/tests/fixtures/routeHarness.ts
@@ -1,33 +1,50 @@
import { Hono } from 'hono';
+import type { AppEnv, AppVariables, Redis } from '../../types/app.ts';
+import type { Env } from '../../types/env.ts';
+
+export interface CallOptions {
+ json?: unknown;
+ env?: Partial<Env>;
+}
+
+export type RouteStep = [method: string, path: string, json?: unknown, env?: Partial<Env>];
+
+export interface RouteResult {
+ status: number;
+ body: string;
+ location?: string;
+}
+
+export type FakeRedis = Redis & { deleted: string[] };
// mounts a router behind a middleware that fills the context the way server.js does
-export function mountWithContext(register, context) {
- const app = new Hono();
+export function mountWithContext(register: (app: Hono<AppEnv>) => unknown, context: Record<string, unknown>): Hono<AppEnv> {
+ const app = new Hono<AppEnv>();
app.use('*', async (c, next) => {
- Object.entries(context).forEach(([key, value]) => c.set(key, value));
+ Object.entries(context).forEach(([key, value]) => c.set(key as keyof AppVariables, value as never));
await next();
});
register(app);
return app;
}
-export async function callRoute(app, method, path, options = {}) {
- const init = { method };
+export async function callRoute(app: Hono<AppEnv>, method: string, path: string, options: CallOptions = {}): Promise<RouteResult> {
+ const init: RequestInit = { method };
if (options.json !== undefined) {
init.body = typeof options.json === 'string' ? options.json : JSON.stringify(options.json);
init.headers = { 'Content-Type': 'application/json' };
}
const response = await app.request(path, init, options.env ?? {});
- const result = { status: response.status, body: await response.text() };
+ const result: RouteResult = { status: response.status, body: await response.text() };
const location = response.headers.get('location');
if (location !== null) result.location = location;
return result;
}
-export function fakeRedis() {
- const deleted = [];
+export function fakeRedis(): FakeRedis {
+ const deleted: string[] = [];
return {
deleted,
- async del(key) { deleted.push(key); },
- };
+ async del(key: string) { deleted.push(key); },
+ } as unknown as FakeRedis;
}
diff --git a/backend/tests/fixtures/youtubeFixtures.ts b/backend/tests/fixtures/youtubeFixtures.ts
index 8ba904d..60ababc 100644
--- a/backend/tests/fixtures/youtubeFixtures.ts
+++ b/backend/tests/fixtures/youtubeFixtures.ts
@@ -1,6 +1,8 @@
+import type { YouTubeVideo } from '../../../shared/types/youtube.ts';
+
export const FIXED_NOW = Date.parse('2026-09-01T12:00:00Z');
-function video(videoId, publishedAt, duration, counts, extra = {}) {
+function video(videoId: string, publishedAt: string, duration: string, counts: [number, number | null, number | null], extra: Record<string, unknown> = {}): YouTubeVideo {
const [viewCount, likeCount, commentCount] = counts;
return {
videoId,
@@ -26,7 +28,7 @@ function video(videoId, publishedAt, duration, counts, extra = {}) {
embeddable: true,
madeForKids: false,
...extra,
- };
+ } as YouTubeVideo;
}
export const richVideos = [
@@ -48,8 +50,8 @@ export const zeroViewVideos = [
video('z2', '2026-08-01T10:00:00Z', 'PT20M', [0, null, null]),
];
-function generatedTags(index) {
- const tags = [];
+function generatedTags(index: number) {
+ const tags: string[] = [];
for (let tag = 0; tag < 40; tag++) {
if ((tag + index) % 4 === 0) tags.push(`Tag${tag}`);
}
@@ -64,7 +66,7 @@ export const generatedVideos = Array.from({ length: 36 }, (_, index) => video(
{ tags: generatedTags(index), categoryId: String(20 + (index % 6)) },
));
-export const rawPlaylistItem = (videoId) => ({ snippet: { resourceId: { videoId } } });
+export const rawPlaylistItem = (videoId: string) => ({ snippet: { resourceId: { videoId } } });
export const rawVideos = {
full: {
diff --git a/backend/tests/lib/cache.test.ts b/backend/tests/lib/cache.test.ts
index 41c4c3e..855ed91 100644
--- a/backend/tests/lib/cache.test.ts
+++ b/backend/tests/lib/cache.test.ts
@@ -4,42 +4,48 @@ import {
getVideosCache, setVideosCache, deleteVideosCache,
getIGCache, setIGCache, getRedditCache, setRedditCache,
} from '../../lib/cache.ts';
+import type { Redis } from '../../types/app.ts';
+import type { VideosCacheData, YouTubeVideo } from '../../../shared/types/youtube.ts';
+import type { IGCacheData } from '../../../shared/types/instagram.ts';
+import type { RedditCacheData } from '../../../shared/types/reddit.ts';
-function memoryRedis() {
- const store = new Map();
+type MemoryRedis = Redis & { store: Map<string, unknown> };
+
+function memoryRedis(): MemoryRedis {
+ const store = new Map<string, unknown>();
return {
store,
- get: async (key) => store.get(key) ?? null,
- set: async (key, value, options) => { store.set(key, value); store.set(`${key}:options`, options); },
- del: async (key) => { store.delete(key); },
- };
+ get: async (key: string) => store.get(key) ?? null,
+ set: async (key: string, value: unknown, options: unknown) => { store.set(key, value); store.set(`${key}:options`, options); },
+ del: async (key: string) => { store.delete(key); },
+ } as unknown as MemoryRedis;
}
const failingRedis = {
get: async () => { throw new Error('down'); },
set: async () => { throw new Error('down'); },
del: async () => { throw new Error('down'); },
-};
+} as unknown as Redis;
test('every helper is a no-op without redis', async () => {
assert.equal(await getVideosCache(null, 'u', 'a'), null);
assert.equal(await getIGCache(null, 'u', 'a'), null);
assert.equal(await getRedditCache(null, 'u', 'a'), null);
- assert.equal(await setVideosCache(null, 'u', 'a', {}), undefined);
+ assert.equal(await setVideosCache(null, 'u', 'a', {} as VideosCacheData), undefined);
assert.equal(await deleteVideosCache(null, 'u', 'a'), undefined);
});
test('redis failures fall back silently', async () => {
assert.equal(await getVideosCache(failingRedis, 'u', 'a'), null);
assert.equal(await getRedditCache(failingRedis, 'u', 'a'), null);
- assert.equal(await setVideosCache(failingRedis, 'u', 'a', { videos: [] }), undefined);
- assert.equal(await setRedditCache(failingRedis, 'u', 'a', {}), undefined);
+ assert.equal(await setVideosCache(failingRedis, 'u', 'a', { videos: [] } as unknown as VideosCacheData), undefined);
+ assert.equal(await setRedditCache(failingRedis, 'u', 'a', {} as RedditCacheData), undefined);
assert.equal(await deleteVideosCache(failingRedis, 'u', 'a'), undefined);
});
test('video entries round-trip with a version and a 6 hour expiry', async () => {
const redis = memoryRedis();
- await setVideosCache(redis, 'u', 'a', { videos: [1] });
+ await setVideosCache(redis, 'u', 'a', { videos: [1] as unknown as YouTubeVideo[] } as VideosCacheData);
assert.deepEqual(await getVideosCache(redis, 'u', 'a'), { videos: [1], version: 2 });
assert.deepEqual(redis.store.get('videos:u:a:options'), { ex: 21600 });
@@ -56,8 +62,8 @@ test('entries written by older code read as a miss', async () => {
test('delete removes the entry', async () => {
const redis = memoryRedis();
- await setIGCache(redis, 'u', 'a', { media: [] });
- await setVideosCache(redis, 'u', 'a', { videos: [] });
+ await setIGCache(redis, 'u', 'a', { media: [] } as unknown as IGCacheData);
+ await setVideosCache(redis, 'u', 'a', { videos: [] } as unknown as VideosCacheData);
await deleteVideosCache(redis, 'u', 'a');
assert.equal(await getVideosCache(redis, 'u', 'a'), null);
diff --git a/backend/tests/lib/safeAccount.test.ts b/backend/tests/lib/safeAccount.test.ts
index 8b5a46c..c88c293 100644
--- a/backend/tests/lib/safeAccount.test.ts
+++ b/backend/tests/lib/safeAccount.test.ts
@@ -2,6 +2,7 @@ import { test } from 'node:test';
import assert from 'node:assert/strict';
import { safeAccount } from '../../lib/safeAccount.ts';
import { buildMediaParams } from '../../services/instagram.ts';
+import type { Account } from '../../../shared/types/domain.ts';
test('safeAccount strips every credential and reports cookie presence', () => {
const out = safeAccount({
@@ -13,7 +14,7 @@ test('safeAccount strips every credential and reports cookie presence', () => {
test('safeAccount does not mutate its input', () => {
const input = { id: 'a1', accessToken: 't' };
- safeAccount(input);
+ safeAccount(input as Account);
assert.equal(input.accessToken, 't');
});
diff --git a/backend/tests/routes/accounts.test.ts b/backend/tests/routes/accounts.test.ts
index 2079e5b..e531f27 100644
--- a/backend/tests/routes/accounts.test.ts
+++ b/backend/tests/routes/accounts.test.ts
@@ -5,8 +5,11 @@ import { test, describe, before, after, beforeEach, afterEach, mock } from 'node
import accountsRouter from '../../routes/accounts.ts';
import { assertGolden } from '../fixtures/golden.ts';
import { installFetch, reply } from '../fixtures/fakeFetch.ts';
+import type { FetchMock, RecordedRequest } from '../fixtures/fakeFetch.ts';
import { fakeSupabase, accountRow } from '../fixtures/fakeSupabase.ts';
+import type { SupabaseCall } from '../fixtures/fakeSupabase.ts';
import { mountWithContext, callRoute, fakeRedis } from '../fixtures/routeHarness.ts';
+import type { RouteStep } from '../fixtures/routeHarness.ts';
// a byte order mark that pasted secrets sometimes start with
const BOM = String.fromCharCode(0xfeff);
@@ -25,7 +28,7 @@ const storedAccounts = [
accountRow({ id: 'other', platform: 'youtube', channelId: CHANNEL_NEW }, 'user-2'),
];
-function channelBody(channelId) {
+function channelBody(channelId: string) {
if (channelId.startsWith('UCmissing')) return { items: [] };
return {
items: [{
@@ -47,7 +50,7 @@ const instagramProfiles = {
NOID: { username: 'ghost' },
};
-function instagramReply(url) {
+function instagramReply(url: URL) {
const params = url.searchParams;
const token = params.get('access_token');
if (url.pathname === '/access_token') {
@@ -58,11 +61,11 @@ function instagramReply(url) {
if (token === 'IGTOKEN') return reply({ access_token: 'IGTOKEN2', expires_in: 86400 });
return reply({ error: { message: 'Token cannot be refreshed' } });
}
- const profile = instagramProfiles[token];
+ const profile = instagramProfiles[token as keyof typeof instagramProfiles];
return profile ? reply(profile) : reply({ error: { message: 'Invalid OAuth access token' } });
}
-function platformServer(request) {
+function platformServer(request: RecordedRequest) {
const url = new URL(request.url);
if (url.hostname === 'graph.instagram.com') return instagramReply(url);
if (url.hostname === 'www.reddit.com') {
@@ -73,27 +76,27 @@ function platformServer(request) {
const params = url.searchParams;
if (params.get('forHandle')) return reply({ items: [{ id: params.get('forHandle') === 'existing' ? CHANNEL_A : CHANNEL_NEW }] });
if (params.get('forUsername') || params.get('q')) return reply({ items: [] });
- return reply(channelBody(params.get('id')));
+ return reply(channelBody(params.get('id')!));
}
-let fetchMock = null;
-let logLines = [];
+let fetchMock: FetchMock | null = null;
+let logLines: unknown[][] = [];
before(() => mock.timers.enable({ apis: ['Date'], now: FIXED_NOW }));
after(() => mock.timers.reset());
beforeEach(() => {
mock.method(Math, 'random', () => 0.123456789);
logLines = [];
- mock.method(console, 'log', (...args) => logLines.push(['log', ...args]));
- mock.method(console, 'error', (...args) => logLines.push(['error', ...args]));
+ mock.method(console, 'log', (...args: unknown[]) => logLines.push(['log', ...args]));
+ mock.method(console, 'error', (...args: unknown[]) => logLines.push(['error', ...args]));
fetchMock = installFetch(platformServer);
});
afterEach(() => {
- fetchMock.restore();
+ fetchMock!.restore();
mock.restoreAll();
});
-async function runScenario(steps, options = {}) {
+async function runScenario(steps: RouteStep[], options: { supabase?: { calls: SupabaseCall[] } } = {}) {
const supabase = options.supabase ?? fakeSupabase(storedAccounts);
const redis = fakeRedis();
const app = mountWithContext(app => app.route('/', accountsRouter), { supabase, redis, userId: 'user-1' });
@@ -101,7 +104,7 @@ async function runScenario(steps, options = {}) {
for (const [method, path, json, env] of steps) {
responses.push(await callRoute(app, method, path, { json, env: env ?? ENV }));
}
- return { responses, requests: fetchMock.requests, calls: supabase.calls, redis: redis.deleted, logs: logLines };
+ return { responses, requests: fetchMock!.requests, calls: supabase.calls, redis: redis.deleted, logs: logLines };
}
const brokenSupabase = { calls: [], from() { throw new Error('database unavailable'); } };
diff --git a/backend/tests/routes/analytics.test.ts b/backend/tests/routes/analytics.test.ts
index 0f7e71b..d125e07 100644
--- a/backend/tests/routes/analytics.test.ts
+++ b/backend/tests/routes/analytics.test.ts
@@ -2,12 +2,30 @@
process.removeAllListeners('warning');
import { test, describe, before, after, afterEach, mock } from 'node:test';
+import type { Mock } from 'node:test';
+import type { Hono } from 'hono';
import analyticsRouter from '../../routes/analytics.ts';
import overviewRouter from '../../routes/overview.ts';
import { assertGolden } from '../fixtures/golden.ts';
import { installFetch, reply } from '../fixtures/fakeFetch.ts';
+import type { FetchMock, RecordedRequest } from '../fixtures/fakeFetch.ts';
import { fakeSupabase, accountRow, tableRow } from '../fixtures/fakeSupabase.ts';
import { mountWithContext, callRoute } from '../fixtures/routeHarness.ts';
+import type { RouteStep } from '../fixtures/routeHarness.ts';
+import type { AppEnv } from '../../types/app.ts';
+import type { Env } from '../../types/env.ts';
+
+interface StoreWrite {
+ key: string;
+ options: unknown;
+ version: unknown;
+}
+
+interface FakeStore {
+ writes: StoreWrite[];
+ get(key: string): Promise<unknown>;
+ set(key: string, value: { version?: unknown }, options: unknown): Promise<void>;
+}
const FIXED_NOW = Date.parse('2026-09-01T12:00:00Z');
const ENV = { YOUTUBE_API_KEY: 'YTKEY' };
@@ -45,16 +63,16 @@ function cachedRedis() {
return fakeStore(store);
}
-function fakeStore(store) {
- const writes = [];
+function fakeStore(store: Record<string, unknown>): FakeStore {
+ const writes: StoreWrite[] = [];
return {
writes,
- async get(key) { return store[key] ?? null; },
- async set(key, value, options) { writes.push({ key, options, version: value.version }); store[key] = value; },
+ async get(key: string) { return store[key] ?? null; },
+ async set(key: string, value: { version?: unknown }, options: unknown) { writes.push({ key, options, version: value.version }); store[key] = value; },
};
}
-function youtubeReply(request) {
+function youtubeReply(request: RecordedRequest) {
const url = new URL(request.url);
const endpoint = url.pathname.split('/').pop();
if (endpoint === 'playlistItems') return reply({ items: [{ snippet: { resourceId: { videoId: 'v1' } } }] });
@@ -67,20 +85,20 @@ function youtubeReply(request) {
return reply({ error: { message: 'Channel lookup failed', errors: [{ reason: 'notFound' }], code: 404 } });
}
-let fetchMock = null;
+let fetchMock: FetchMock | null = null;
afterEach(() => fetchMock?.restore());
-async function runCalls(router, calls, { redis = null, env = ENV } = {}) {
+async function runCalls(router: Hono<AppEnv>, calls: RouteStep[], { redis = null, env = ENV }: { redis?: FakeStore | null; env?: Partial<Env> } = {}) {
const supabase = fakeSupabase(ROWS);
const app = mountWithContext(server => server.route('/', router), { supabase, redis, userId: 'user-1' });
fetchMock = installFetch(youtubeReply);
- const logLines = [];
- mock.method(console, 'error', (...args) => logLines.push(['error', ...args]));
+ const logLines: unknown[][] = [];
+ mock.method(console, 'error', (...args: unknown[]) => logLines.push(['error', ...args]));
const responses = [];
for (const [method, path] of calls) {
responses.push({ call: `${method} ${path}`, ...(await callRoute(app, method, path, { env })) });
}
- console.error.mock.restore();
+ (console.error as Mock<typeof console.error>).mock.restore();
return { responses, queries: supabase.calls, requests: fetchMock.requests, logLines, redisWrites: redis?.writes ?? null };
}
@@ -121,8 +139,8 @@ describe('analytics and overview routes golden output', () => {
const redis = fakeStore({});
const app = mountWithContext(server => server.route('/', overviewRouter), { supabase, redis, userId: 'user-1' });
fetchMock = installFetch(() => reply({}));
- const background = [];
- const executionCtx = { waitUntil: promise => background.push(promise), passThroughOnException() {} };
+ const background: Promise<unknown>[] = [];
+ const executionCtx = { waitUntil: (promise: Promise<unknown>) => background.push(promise), passThroughOnException() {} } as unknown as ExecutionContext;
const response = await app.request('/overview', { method: 'GET' }, ENV, executionCtx);
const body = await response.text();
const settled = await Promise.all(background);
diff --git a/backend/tests/routes/instagramAuth.test.ts b/backend/tests/routes/instagramAuth.test.ts
index 35014f4..28d449e 100644
--- a/backend/tests/routes/instagramAuth.test.ts
+++ b/backend/tests/routes/instagramAuth.test.ts
@@ -6,7 +6,9 @@ import { urlHandler, callbackHandler } from '../../routes/instagramAuth.ts';
import { createOAuthState } from '../../lib/cache.ts';
import { assertGolden } from '../fixtures/golden.ts';
import { installFetch, reply } from '../fixtures/fakeFetch.ts';
+import type { FetchMock, RecordedRequest } from '../fixtures/fakeFetch.ts';
import { fakeSupabase, accountRow } from '../fixtures/fakeSupabase.ts';
+import type { FakeSupabase } from '../fixtures/fakeSupabase.ts';
import { mountWithContext, callRoute } from '../fixtures/routeHarness.ts';
// a byte order mark that pasted secrets sometimes start with
@@ -29,40 +31,40 @@ const profiles = {
// the short token returned for each authorization code decides the rest of the flow
const shortTokens = { good: 'SHORT_GOOD', fallback: 'SHORT_FALLBACK', noid: 'SHORT_NOID', dup: 'SHORT_DUP' };
-function instagramServer(request) {
+function instagramServer(request: RecordedRequest) {
const url = new URL(request.url);
if (url.hostname === 'api.instagram.com') {
const code = new URLSearchParams(request.body).get('code');
if (code === 'bad') return reply({ error_type: 'OAuthException', code: 400, error_message: 'Invalid authorization code' });
if (code === 'weird') return reply({ unexpected: 'x'.repeat(200) });
if (code === 'offline') return new Error('getaddrinfo ENOTFOUND api.instagram.com');
- return reply({ access_token: shortTokens[code], user_id: 1 });
+ return reply({ access_token: shortTokens[code as keyof typeof shortTokens], user_id: 1 });
}
const token = url.searchParams.get('access_token');
if (url.pathname === '/access_token') {
if (token === 'SHORT_GOOD') return reply({ access_token: 'LONG', token_type: 'bearer', expires_in: 5183944 });
return reply({ error: { message: 'Unsupported request' } });
}
- return reply(profiles[token] ?? { error: { message: 'Invalid OAuth access token' } });
+ return reply(profiles[token as keyof typeof profiles] ?? { error: { message: 'Invalid OAuth access token' } });
}
-let fetchMock = null;
-let logLines = [];
+let fetchMock: FetchMock | null = null;
+let logLines: unknown[][] = [];
before(() => mock.timers.enable({ apis: ['Date'], now: FIXED_NOW }));
after(() => mock.timers.reset());
beforeEach(() => {
mock.method(Math, 'random', () => 0.987654321);
logLines = [];
- mock.method(console, 'error', (...args) => logLines.push(['error', ...args]));
+ mock.method(console, 'error', (...args: unknown[]) => logLines.push(['error', ...args]));
fetchMock = installFetch(instagramServer);
});
afterEach(() => {
- fetchMock.restore();
+ fetchMock!.restore();
mock.restoreAll();
});
-function buildApp(supabase) {
+function buildApp(supabase: FakeSupabase) {
return mountWithContext(app => {
app.get('/url', urlHandler);
app.get('/callback', callbackHandler);
@@ -109,6 +111,6 @@ describe('instagram oauth golden output', () => {
const responses = [];
for (const path of paths) responses.push(await callRoute(app, 'GET', path, { env: ENV }));
responses.push(await callRoute(app, 'GET', `/callback?code=good&state=${validState}`, { env: {} }));
- assertGolden({ responses, requests: fetchMock.requests, calls: supabase.calls, logs: logLines }, 'instagramAuth.callback');
+ assertGolden({ responses, requests: fetchMock!.requests, calls: supabase.calls, logs: logLines }, 'instagramAuth.callback');
});
});
diff --git a/backend/tests/routes/trackedContent.test.ts b/backend/tests/routes/trackedContent.test.ts
index 481ed22..13166da 100644
--- a/backend/tests/routes/trackedContent.test.ts
+++ b/backend/tests/routes/trackedContent.test.ts
@@ -1,9 +1,14 @@
import { test, describe, before, after, afterEach, mock } from 'node:test';
+import type { Mock } from 'node:test';
import trackedContentRouter from '../../routes/trackedContent.ts';
import { assertGolden } from '../fixtures/golden.ts';
import { installFetch, reply } from '../fixtures/fakeFetch.ts';
+import type { FetchMock } from '../fixtures/fakeFetch.ts';
import { fakeSupabase, accountRow, tableRow } from '../fixtures/fakeSupabase.ts';
+import type { Row } from '../fixtures/fakeSupabase.ts';
import { mountWithContext, callRoute } from '../fixtures/routeHarness.ts';
+import type { RouteStep } from '../fixtures/routeHarness.ts';
+import type { Env } from '../../types/env.ts';
const FIXED_NOW = Date.parse('2026-09-01T12:00:00Z');
const ENV = { YOUTUBE_API_KEY: 'YTKEY' };
@@ -11,7 +16,7 @@ const ENV = { YOUTUBE_API_KEY: 'YTKEY' };
const REDDIT_POST = [{ data: { children: [{ data: { id: 'p1', title: 'Tracked', subreddit: 'webdev', score: 77, upvote_ratio: 0.93, num_comments: 8, permalink: '/r/webdev/comments/p1/tracked/', over_18: false, created_utc: 1785000000 } }] } }];
const YOUTUBE_VIDEO = { items: [{ snippet: { title: 'Watch', channelTitle: 'Ribbon', channelId: 'UC1', publishedAt: '2026-08-01T10:00:00Z', thumbnails: { medium: { url: 'm' } } }, statistics: { viewCount: '1500', likeCount: '40', commentCount: '3' } }] };
-function trackedRow(id, contentType, extra = {}) {
+function trackedRow(id: string, contentType: string, extra: { accountId?: string; url?: string; data?: Row } = {}) {
return tableRow('tracked_posts', { id, user_id: 'user-1', account_id: extra.accountId ?? null, url: extra.url ?? `https://example/${id}`, label: '', category: '', content_type: contentType, created_at: '2026-08-01T00:00:00Z', updated_at: '2026-08-01T00:00:00Z', data: extra.data ?? {} });
}
@@ -25,20 +30,20 @@ function seedRows() {
];
}
-let fetchMock = null;
+let fetchMock: FetchMock | null = null;
afterEach(() => fetchMock?.restore());
-async function runCalls(calls, env = ENV) {
+async function runCalls(calls: RouteStep[], env: Partial<Env> = ENV) {
const supabase = fakeSupabase(seedRows());
const app = mountWithContext(server => server.route('/', trackedContentRouter), { supabase, userId: 'user-1' });
fetchMock = installFetch(request => (request.url.includes('googleapis') ? reply(YOUTUBE_VIDEO) : reply(REDDIT_POST)));
const responses = [];
- const logLines = [];
- mock.method(console, 'error', (...args) => logLines.push(['error', ...args]));
+ const logLines: unknown[][] = [];
+ mock.method(console, 'error', (...args: unknown[]) => logLines.push(['error', ...args]));
for (const [method, path, json] of calls) {
responses.push({ call: `${method} ${path}`, ...(await callRoute(app, method, path, { json, env })) });
}
- console.error.mock.restore();
+ (console.error as Mock<typeof console.error>).mock.restore();
return { responses, queries: supabase.calls, requests: fetchMock.requests, logLines };
}
diff --git a/backend/tests/services/accountFactory.test.ts b/backend/tests/services/accountFactory.test.ts
index 8038508..44b987f 100644
--- a/backend/tests/services/accountFactory.test.ts
+++ b/backend/tests/services/accountFactory.test.ts
@@ -3,6 +3,8 @@ import assert from 'node:assert/strict';
import {
newAccountId, tokenExpiryIso, buildYouTubeAccount, buildRedditAccount, buildInstagramAccount,
} from '../../services/accountFactory.ts';
+import type { YouTubeChannelData } from '../../../shared/types/youtube.ts';
+import type { RedditProfile } from '../../../shared/types/reddit.ts';
const FIXED_NOW = Date.parse('2026-09-01T12:00:00Z');
const NOW_ISO = '2026-09-01T12:00:00.000Z';
@@ -21,7 +23,7 @@ describe('accountFactory', () => {
test('tokenExpiryIso adds seconds to now, or returns null without a lifetime', () => {
assert.equal(tokenExpiryIso(3600), '2026-09-01T13:00:00.000Z');
assert.equal(tokenExpiryIso(0), null);
- assert.equal(tokenExpiryIso(undefined), null);
+ assert.equal(tokenExpiryIso(undefined as unknown as number), null);
});
test('buildYouTubeAccount copies the channel fields in a fixed order', () => {
@@ -30,7 +32,7 @@ describe('accountFactory', () => {
thumbnails: { default: 'd' }, subscriberCount: 1, viewCount: 2, videoCount: 3, hiddenSubscriberCount: false,
uploadsPlaylistId: 'UU1', keywords: 'k', topicCategories: ['t'], madeForKids: false, bannerUrl: 'ignored',
};
- const account = buildYouTubeAccount(channelData);
+ const account = buildYouTubeAccount(channelData as unknown as YouTubeChannelData);
assert.deepStrictEqual(Object.keys(account), [
'id', 'channelId', 'title', 'description', 'customUrl', 'publishedAt', 'country', 'thumbnails',
'subscriberCount', 'viewCount', 'videoCount', 'hiddenSubscriberCount', 'uploadsPlaylistId', 'keywords',
@@ -43,7 +45,7 @@ describe('accountFactory', () => {
test('buildRedditAccount keeps the cookie and prefixes the title', () => {
const profile = { username: 'ribbon', totalKarma: 3, postKarma: 2, commentKarma: 1, iconUrl: 'i', createdAt: 'c', isGold: true };
- assert.deepStrictEqual(buildRedditAccount(profile, 'COOKIE'), {
+ assert.deepStrictEqual(buildRedditAccount(profile as RedditProfile, 'COOKIE'), {
id: ACCOUNT_ID, platform: 'reddit', username: 'ribbon', title: 'u/ribbon',
totalKarma: 3, postKarma: 2, commentKarma: 1, iconUrl: 'i', createdAt: 'c', cookie: 'COOKIE',
addedAt: NOW_ISO, lastUpdated: NOW_ISO,
diff --git a/backend/tests/services/analyticsMath.test.ts b/backend/tests/services/analyticsMath.test.ts
index 8cace8e..f9f51d6 100644
--- a/backend/tests/services/analyticsMath.test.ts
+++ b/backend/tests/services/analyticsMath.test.ts
@@ -8,7 +8,7 @@ import {
} from '../../services/analyticsMath.ts';
const NOW = Date.parse('2026-09-01T12:00:00Z');
-const daysAgo = (days) => new Date(NOW - days * DAY_MS);
+const daysAgo = (days: number) => new Date(NOW - days * DAY_MS);
describe('analyticsMath', () => {
test('day names start on Sunday like Date#getDay', () => {
@@ -18,7 +18,7 @@ describe('analyticsMath', () => {
test('sumOf and roundedAverage', () => {
assert.equal(sumOf([{ score: 2 }, { score: 5 }], item => item.score), 7);
- assert.equal(sumOf([], item => item.score), 0);
+ assert.equal(sumOf<{ score: number }>([], item => item.score), 0);
assert.equal(roundedAverage(7, 2), 4);
assert.equal(roundedAverage(7, 0), 0);
});
diff --git a/backend/tests/services/instagram.test.ts b/backend/tests/services/instagram.test.ts
index 7c8d592..4489411 100644
--- a/backend/tests/services/instagram.test.ts
+++ b/backend/tests/services/instagram.test.ts
@@ -8,8 +8,11 @@ import {
summarizeContentTypes,
computeInstagramAnalytics,
} from '../../services/instagram.ts';
+import type { InstagramApiMedia } from '../../services/instagram.ts';
+import type { AnalyticsProfile } from '../../services/instagramAnalytics.ts';
+import type { InstagramMedia } from '../../../shared/types/instagram.ts';
-const viewsInsight = (value) => ({ data: [{ name: 'views', period: 'lifetime', values: [{ value }] }] });
+const viewsInsight = (value: unknown) => ({ data: [{ name: 'views', period: 'lifetime', values: [{ value }] }] }) as unknown as InstagramApiMedia['insights'];
describe('classifyInstagramMedia', () => {
test('reel reported as VIDEO with REELS product type is a reel', () => {
@@ -92,14 +95,14 @@ describe('fetchInstagramMedia', () => {
afterEach(() => { globalThis.fetch = originalFetch; });
test('retries a page without insights when the insights request fails', async () => {
- const requests = [];
- globalThis.fetch = async (url) => {
- const fields = new URL(url).searchParams.get('fields');
+ const requests: (string | null)[] = [];
+ globalThis.fetch = async (url: unknown): Promise<Response> => {
+ const fields = new URL(url as string).searchParams.get('fields');
requests.push(fields);
- if (fields.includes('insights')) {
- return { json: async () => ({ error: { message: 'Media posted before business account conversion' } }) };
+ if (fields!.includes('insights')) {
+ return { json: async () => ({ error: { message: 'Media posted before business account conversion' } }) } as unknown as Response;
}
- return { json: async () => ({ data: [{ id: 'a', media_type: 'VIDEO', media_product_type: 'REELS' }] }) };
+ return { json: async () => ({ data: [{ id: 'a', media_type: 'VIDEO', media_product_type: 'REELS' }] }) } as unknown as Response;
};
const media = await fetchInstagramMedia('123', 'token', 500);
@@ -114,9 +117,9 @@ describe('fetchInstagramMedia', () => {
'': { data: [{ id: 'a', media_type: 'IMAGE' }, { id: 'b', media_type: 'VIDEO', media_product_type: 'REELS', insights: viewsInsight(5) }], paging: { cursors: { after: 'p2' }, next: 'https://next' } },
p2: { data: [{ id: 'b', media_type: 'VIDEO', media_product_type: 'REELS' }, { id: 'c', media_type: 'VIDEO', media_product_type: 'FEED' }], paging: { cursors: { after: 'p3' } } },
};
- globalThis.fetch = async (url) => {
- const after = new URL(url).searchParams.get('after') ?? '';
- return { json: async () => pages[after] };
+ globalThis.fetch = async (url: unknown): Promise<Response> => {
+ const after = new URL(url as string).searchParams.get('after') ?? '';
+ return { json: async () => pages[after as keyof typeof pages] } as unknown as Response;
};
const media = await fetchInstagramMedia('123', 'token', 500);
@@ -134,7 +137,7 @@ describe('content type tracking', () => {
{ id: '2', contentType: 'reel', likeCount: 11, commentsCount: 8, viewCount: null, timestamp: '2026-08-21T10:00:00+0000', caption: '' },
{ id: '3', contentType: 'post', likeCount: 2, commentsCount: 0, viewCount: 50, timestamp: '2026-06-01T10:00:00+0000', caption: '' },
{ id: '4', contentType: 'video', likeCount: 7, commentsCount: 1, viewCount: 300, timestamp: '2025-01-01T10:00:00+0000', caption: '' },
- ];
+ ] as InstagramMedia[];
test('summarizeContentTypes counts each item exactly once', () => {
const summary = summarizeContentTypes(media);
@@ -166,7 +169,7 @@ describe('content type tracking', () => {
});
test('computeInstagramAnalytics returns empty type stats with no media', () => {
- const analytics = computeInstagramAnalytics({ mediaCount: 0 }, []);
+ const analytics = computeInstagramAnalytics({ mediaCount: 0 } as AnalyticsProfile, []);
assert.equal(analytics.totalViews, 0);
assert.equal(analytics.contentTypeStats.reel.count, 0);
assert.equal(analytics.contentTypeStats.video.avgViews, 0);
diff --git a/backend/tests/services/instagramAnalytics.test.ts b/backend/tests/services/instagramAnalytics.test.ts
index a6ead0e..033157b 100644
--- a/backend/tests/services/instagramAnalytics.test.ts
+++ b/backend/tests/services/instagramAnalytics.test.ts
@@ -2,6 +2,7 @@ process.env.TZ = 'UTC';
import { test, describe, before, after, mock } from 'node:test';
import { computeInstagramAnalytics } from '../../services/instagramAnalytics.ts';
+import type { AnalyticsProfile } from '../../services/instagramAnalytics.ts';
import { assertGolden } from '../fixtures/golden.ts';
import { FIXED_NOW, richMedia, zeroEngagementMedia, generatedMedia } from '../fixtures/instagramFixtures.ts';
@@ -11,8 +12,8 @@ describe('computeInstagramAnalytics golden output', () => {
test('empty and missing media return the empty state', () => {
assertGolden({
- empty: computeInstagramAnalytics({ mediaCount: 7 }, []),
- missing: computeInstagramAnalytics({}, null),
+ empty: computeInstagramAnalytics({ mediaCount: 7 } as AnalyticsProfile, []),
+ missing: computeInstagramAnalytics({} as AnalyticsProfile, null),
}, 'instagramAnalytics.empty');
});
@@ -26,13 +27,13 @@ describe('computeInstagramAnalytics golden output', () => {
test('one and two items cover the odd and even medians', () => {
assertGolden({
- single: computeInstagramAnalytics({ followersCount: 10 }, richMedia.slice(0, 1)),
- pair: computeInstagramAnalytics({ followersCount: 10 }, richMedia.slice(1, 3)),
+ single: computeInstagramAnalytics({ followersCount: 10 } as AnalyticsProfile, richMedia.slice(0, 1)),
+ pair: computeInstagramAnalytics({ followersCount: 10 } as AnalyticsProfile, richMedia.slice(1, 3)),
}, 'instagramAnalytics.small');
});
test('media with no engagement at all', () => {
- assertGolden(computeInstagramAnalytics({ followersCount: 50 }, zeroEngagementMedia), 'instagramAnalytics.zero');
+ assertGolden(computeInstagramAnalytics({ followersCount: 50 } as AnalyticsProfile, zeroEngagementMedia), 'instagramAnalytics.zero');
});
test('more than twenty items with many hashtags', () => {
diff --git a/backend/tests/services/instagramApi.test.ts b/backend/tests/services/instagramApi.test.ts
index 708633e..a6f2512 100644
--- a/backend/tests/services/instagramApi.test.ts
+++ b/backend/tests/services/instagramApi.test.ts
@@ -2,15 +2,16 @@ import { test, describe, afterEach } from 'node:test';
import { fetchInstagramProfile } from '../../services/instagramApi.ts';
import { assertGolden } from '../fixtures/golden.ts';
import { installFetch, reply } from '../fixtures/fakeFetch.ts';
+import type { FetchMock } from '../fixtures/fakeFetch.ts';
-let fetchMock = null;
+let fetchMock: FetchMock | null = null;
afterEach(() => fetchMock?.restore());
-async function outcomeOf(promise) {
+async function outcomeOf(promise: Promise<unknown>) {
try {
return { value: await promise };
} catch (err) {
- return { error: err.message };
+ return { error: (err as Error).message };
}
}
diff --git a/backend/tests/services/instagramContentTypes.test.ts b/backend/tests/services/instagramContentTypes.test.ts
index 2af5250..64b3a2e 100644
--- a/backend/tests/services/instagramContentTypes.test.ts
+++ b/backend/tests/services/instagramContentTypes.test.ts
@@ -2,6 +2,7 @@ import { test, describe } from 'node:test';
import { CONTENT_TYPES, summarizeContentTypes } from '../../services/instagramContentTypes.ts';
import { assertGolden } from '../fixtures/golden.ts';
import { richMedia, generatedMedia } from '../fixtures/instagramFixtures.ts';
+import type { InstagramMedia } from '../../../shared/types/instagram.ts';
describe('summarizeContentTypes golden output', () => {
test('summarizes media of every type, unknown types and missing counts', () => {
@@ -14,7 +15,7 @@ describe('summarizeContentTypes golden output', () => {
types: CONTENT_TYPES,
rich: summarizeContentTypes(richMedia),
generated: summarizeContentTypes(generatedMedia),
- odd: summarizeContentTypes(odd),
+ odd: summarizeContentTypes(odd as unknown as InstagramMedia[]),
missing: summarizeContentTypes(null),
}, 'instagramContentTypes.summary');
});
diff --git a/backend/tests/services/instagramMedia.test.ts b/backend/tests/services/instagramMedia.test.ts
index 5f33412..ed4a037 100644
--- a/backend/tests/services/instagramMedia.test.ts
+++ b/backend/tests/services/instagramMedia.test.ts
@@ -1,9 +1,11 @@
import { test, describe, afterEach } from 'node:test';
import { classifyInstagramMedia, extractInstagramViews, normalizeInstagramMedia, fetchInstagramMedia } from '../../services/instagramMedia.ts';
+import type { InstagramApiMedia } from '../../services/instagramMedia.ts';
import { assertGolden } from '../fixtures/golden.ts';
import { installFetch, reply } from '../fixtures/fakeFetch.ts';
+import type { FetchMock } from '../fixtures/fakeFetch.ts';
-let fetchMock = null;
+let fetchMock: FetchMock | null = null;
afterEach(() => fetchMock?.restore());
const rawItems = [
@@ -14,7 +16,7 @@ const rawItems = [
{ id: '5', permalink: 'https://instagram.com/reels/5/', insights: { data: [{ name: 'views', values: [{ value: null }] }] } },
{ id: '6', media_type: 'reel', insights: { data: [{ name: 'views', values: [{ value: 'Infinity' }] }] } },
{ id: '7' },
-];
+] as unknown as InstagramApiMedia[];
describe('instagram media golden output', () => {
test('classifies, reads views and normalizes raw items', () => {
@@ -29,7 +31,7 @@ describe('instagram media golden output', () => {
fetchMock = installFetch((request) => {
const params = new URL(request.url).searchParams;
const after = params.get('after') ?? '';
- if (after === 'p2' && params.get('fields').includes('insights')) return reply({ error: { message: 'insights unavailable' } });
+ if (after === 'p2' && params.get('fields')!.includes('insights')) return reply({ error: { message: 'insights unavailable' } });
if (after === '') return reply({ data: [rawItems[0], rawItems[1], null, { media_type: 'IMAGE' }], paging: { next: 'https://next', cursors: { after: 'p2' } } });
if (after === 'p2') return reply({ data: [rawItems[1], rawItems[2]], paging: { next: 'https://next', cursors: { after: 'p3' } } });
return reply({ data: [rawItems[3]], paging: { cursors: { after: 'p4' } } });
diff --git a/backend/tests/services/instagramPublishing.test.ts b/backend/tests/services/instagramPublishing.test.ts
index 0484a1d..399a7fc 100644
--- a/backend/tests/services/instagramPublishing.test.ts
+++ b/backend/tests/services/instagramPublishing.test.ts
@@ -1,6 +1,7 @@
import { test, describe } from 'node:test';
import { buildMediaParams } from '../../services/instagramPublishing.ts';
import { assertGolden } from '../fixtures/golden.ts';
+import type { InstagramPublishMediaType } from '../../../shared/types/instagram.ts';
const fullPost = {
mediaUrl: 'https://cdn.example/file.jpg',
@@ -25,7 +26,7 @@ const emptyPost = {
thumbOffset: null,
};
-const mediaTypes = ['CAROUSEL', 'CAROUSEL_ITEM_IMAGE', 'CAROUSEL_ITEM_VIDEO', 'REELS', 'STORIES', 'IMAGE', undefined];
+const mediaTypes: (InstagramPublishMediaType | undefined)[] = ['CAROUSEL', 'CAROUSEL_ITEM_IMAGE', 'CAROUSEL_ITEM_VIDEO', 'REELS', 'STORIES', 'IMAGE', undefined];
describe('buildMediaParams golden output', () => {
test('builds container parameters for every media type, full and empty', () => {
diff --git a/backend/tests/services/instagramTokens.test.ts b/backend/tests/services/instagramTokens.test.ts
index e755104..1e8ec4b 100644
--- a/backend/tests/services/instagramTokens.test.ts
+++ b/backend/tests/services/instagramTokens.test.ts
@@ -2,11 +2,13 @@ import { test, describe, before, after, afterEach, mock } from 'node:test';
import { exchangeForLongLivedToken, refreshLongLivedToken, autoRefreshInstagramTokens } from '../../services/instagramTokens.ts';
import { assertGolden } from '../fixtures/golden.ts';
import { installFetch, reply } from '../fixtures/fakeFetch.ts';
+import type { FetchMock } from '../fixtures/fakeFetch.ts';
import { fakeSupabase, accountRow } from '../fixtures/fakeSupabase.ts';
import { FIXED_NOW } from '../fixtures/instagramFixtures.ts';
+import type { SupabaseClient } from '../../types/app.ts';
const DAY_MS = 86400000;
-let fetchMock = null;
+let fetchMock: FetchMock | null = null;
before(() => mock.timers.enable({ apis: ['Date'], now: FIXED_NOW }));
after(() => mock.timers.reset());
@@ -15,22 +17,22 @@ afterEach(() => {
mock.restoreAll();
});
-async function outcomeOf(promise) {
+async function outcomeOf(promise: Promise<unknown>) {
try {
return { value: await promise };
} catch (err) {
- return { error: err.message };
+ return { error: (err as Error).message };
}
}
function captureConsole() {
- const lines = [];
- mock.method(console, 'log', (...args) => lines.push(['log', ...args]));
- mock.method(console, 'error', (...args) => lines.push(['error', ...args]));
+ const lines: unknown[][] = [];
+ mock.method(console, 'log', (...args: unknown[]) => lines.push(['log', ...args]));
+ mock.method(console, 'error', (...args: unknown[]) => lines.push(['error', ...args]));
return lines;
}
-function expiresIn(days) {
+function expiresIn(days: number) {
return new Date(FIXED_NOW + days * DAY_MS).toISOString();
}
@@ -73,7 +75,7 @@ describe('autoRefreshInstagramTokens golden output', () => {
T6: { error: { message: 'Session has expired' } },
T7: { access_token: 'N7' },
};
- fetchMock = installFetch((request) => reply(bodies[new URL(request.url).searchParams.get('access_token')]));
+ fetchMock = installFetch((request) => reply(bodies[new URL(request.url).searchParams.get('access_token') as keyof typeof bodies]));
const lines = captureConsole();
await autoRefreshInstagramTokens(supabase);
assertGolden({ lines, requests: fetchMock.requests, calls: supabase.calls, table: supabase.table }, 'instagramTokens.autoRefresh');
@@ -85,7 +87,7 @@ describe('autoRefreshInstagramTokens golden output', () => {
const notDue = fakeSupabase([accountRow({ id: 'b1', platform: 'instagram', accessToken: 'T', tokenExpiresAt: expiresIn(30) })]);
await autoRefreshInstagramTokens(notDue);
await autoRefreshInstagramTokens(fakeSupabase([]));
- await autoRefreshInstagramTokens({ from() { throw new Error('database unavailable'); } });
+ await autoRefreshInstagramTokens({ from() { throw new Error('database unavailable'); } } as unknown as SupabaseClient);
assertGolden({ lines, requests: fetchMock.requests, calls: notDue.calls }, 'instagramTokens.idle');
});
});
diff --git a/backend/tests/services/reddit.test.ts b/backend/tests/services/reddit.test.ts
index 2b13c69..3e984f9 100644
--- a/backend/tests/services/reddit.test.ts
+++ b/backend/tests/services/reddit.test.ts
@@ -2,20 +2,21 @@ import { test, describe, before, after, afterEach, mock } from 'node:test';
import { fetchRedditProfile, fetchRedditPosts, fetchTrackedPostData, autoRefreshRedditSessions } from '../../services/reddit.ts';
import { assertGolden } from '../fixtures/golden.ts';
import { installFetch, reply } from '../fixtures/fakeFetch.ts';
+import type { FetchMock } from '../fixtures/fakeFetch.ts';
import { FIXED_NOW, rawRedditPosts } from '../fixtures/redditFixtures.ts';
-let fetchMock = null;
+let fetchMock: FetchMock | null = null;
afterEach(() => fetchMock?.restore());
-async function outcomeOf(promise) {
+async function outcomeOf(promise: Promise<unknown>) {
try {
return { value: await promise };
} catch (err) {
- return { error: err.message };
+ return { error: (err as Error).message };
}
}
-function listing(children, after = null) {
+function listing(children: unknown[], after: string | null = null) {
return reply({ data: { children: children.map(data => ({ data })), after } });
}
diff --git a/backend/tests/services/redditAnalytics.test.ts b/backend/tests/services/redditAnalytics.test.ts
index a08963e..c673e05 100644
--- a/backend/tests/services/redditAnalytics.test.ts
+++ b/backend/tests/services/redditAnalytics.test.ts
@@ -4,8 +4,9 @@ import { test, describe, before, after, mock } from 'node:test';
import { computeRedditAnalytics } from '../../services/redditAnalytics.ts';
import { assertGolden } from '../fixtures/golden.ts';
import { FIXED_NOW, richPosts, zeroScorePosts, generatedPosts } from '../fixtures/redditFixtures.ts';
+import type { RedditProfile } from '../../../shared/types/reddit.ts';
-const profile = { username: 'ribbon', totalKarma: 900 };
+const profile = { username: 'ribbon', totalKarma: 900 } as RedditProfile;
describe('computeRedditAnalytics golden output', () => {
before(() => mock.timers.enable({ apis: ['Date'], now: FIXED_NOW }));
diff --git a/backend/tests/services/youtube.test.ts b/backend/tests/services/youtube.test.ts
index f82f322..8018233 100644
--- a/backend/tests/services/youtube.test.ts
+++ b/backend/tests/services/youtube.test.ts
@@ -5,21 +5,21 @@ import { resolveChannelId, fetchTrackedYouTubeData } from '../../services/youtub
const realFetch = globalThis.fetch;
afterEach(() => { globalThis.fetch = realFetch; });
-function lookupName({ pathname, searchParams }) {
+function lookupName({ pathname, searchParams }: URL) {
if (searchParams.get('forHandle')) return 'forHandle';
if (searchParams.get('forUsername')) return 'forUsername';
return pathname.split('/').pop();
}
// answers each youtube endpoint from a table and records the calls
-function fakeYouTube(responses) {
- const calls = [];
- globalThis.fetch = async (url) => {
- const lookup = lookupName(new URL(url));
+function fakeYouTube(responses: Record<string, unknown>) {
+ const calls: (string | undefined)[] = [];
+ globalThis.fetch = async (url: unknown): Promise<Response> => {
+ const lookup = lookupName(new URL(url as string));
calls.push(lookup);
- const body = responses[lookup] ?? { items: [] };
+ const body = responses[lookup as string] ?? { items: [] };
if (body instanceof Error) throw body;
- return { json: async () => body };
+ return { json: async () => body } as unknown as Response;
};
return calls;
}
@@ -59,10 +59,10 @@ test('an unparseable video link is rejected before any api call', async () => {
});
test('watch, short, embed and youtu.be links all reach the api with the video id', async () => {
- const ids = [];
- globalThis.fetch = async (url) => {
- ids.push(new URL(url).searchParams.get('id'));
- return { json: async () => ({ items: [] }) };
+ const ids: (string | null)[] = [];
+ globalThis.fetch = async (url: unknown): Promise<Response> => {
+ ids.push(new URL(url as string).searchParams.get('id'));
+ return { json: async () => ({ items: [] }) } as unknown as Response;
};
const links = [
'https://www.youtube.com/watch?v=aaa',
diff --git a/backend/tests/services/youtubeChannels.test.ts b/backend/tests/services/youtubeChannels.test.ts
index 207cbc1..ee8377f 100644
--- a/backend/tests/services/youtubeChannels.test.ts
+++ b/backend/tests/services/youtubeChannels.test.ts
@@ -2,15 +2,17 @@ import { test, describe, afterEach } from 'node:test';
import { resolveChannelId, fetchChannelData } from '../../services/youtubeChannels.ts';
import { assertGolden } from '../fixtures/golden.ts';
import { installFetch, reply } from '../fixtures/fakeFetch.ts';
+import type { FetchMock } from '../fixtures/fakeFetch.ts';
+import type { YouTubeApiError } from '../../services/youtubeApi.ts';
-let fetchMock = null;
+let fetchMock: FetchMock | null = null;
afterEach(() => fetchMock?.restore());
-async function outcomeOf(promise) {
+async function outcomeOf(promise: Promise<unknown>) {
try {
return { value: await promise };
} catch (err) {
- return { error: err.message, reason: err.reason, status: err.status };
+ return { error: (err as YouTubeApiError).message, reason: (err as YouTubeApiError).reason, status: (err as YouTubeApiError).status };
}
}
diff --git a/backend/tests/services/youtubeTracked.test.ts b/backend/tests/services/youtubeTracked.test.ts
index 28a4a00..a956fa2 100644
--- a/backend/tests/services/youtubeTracked.test.ts
+++ b/backend/tests/services/youtubeTracked.test.ts
@@ -2,16 +2,17 @@ import { test, describe, before, after, afterEach, mock } from 'node:test';
import { fetchTrackedYouTubeData } from '../../services/youtubeTracked.ts';
import { assertGolden } from '../fixtures/golden.ts';
import { installFetch, reply } from '../fixtures/fakeFetch.ts';
+import type { FetchMock } from '../fixtures/fakeFetch.ts';
import { FIXED_NOW } from '../fixtures/youtubeFixtures.ts';
-let fetchMock = null;
+let fetchMock: FetchMock | null = null;
afterEach(() => fetchMock?.restore());
-async function outcomeOf(promise) {
+async function outcomeOf(promise: Promise<unknown>) {
try {
return { value: await promise };
} catch (err) {
- return { error: err.message };
+ return { error: (err as Error).message };
}
}
diff --git a/backend/tests/services/youtubeVideos.test.ts b/backend/tests/services/youtubeVideos.test.ts
index d2c4278..751265a 100644
--- a/backend/tests/services/youtubeVideos.test.ts
+++ b/backend/tests/services/youtubeVideos.test.ts
@@ -2,29 +2,31 @@ import { test, describe, afterEach } from 'node:test';
import { fetchAllVideos } from '../../services/youtubeVideos.ts';
import { assertGolden } from '../fixtures/golden.ts';
import { installFetch, reply } from '../fixtures/fakeFetch.ts';
+import type { FetchMock, FakeReply } from '../fixtures/fakeFetch.ts';
import { rawPlaylistItem, rawVideos } from '../fixtures/youtubeFixtures.ts';
+import type { YouTubeApiError } from '../../services/youtubeApi.ts';
-let fetchMock = null;
+let fetchMock: FetchMock | null = null;
afterEach(() => fetchMock?.restore());
-async function outcomeOf(promise) {
+async function outcomeOf(promise: Promise<unknown>) {
try {
return { value: await promise };
} catch (err) {
- return { error: err.message, reason: err.reason, status: err.status };
+ return { error: (err as YouTubeApiError).message, reason: (err as YouTubeApiError).reason, status: (err as YouTubeApiError).status };
}
}
-function apiError(message, reason, code) {
+function apiError(message: string, reason?: string, code?: number) {
const errors = reason === undefined ? undefined : [{ reason }];
return reply({ error: { message, errors, code } });
}
-function youtubeServer(playlistPages) {
+function youtubeServer(playlistPages: Record<string, FakeReply>) {
return installFetch((request) => {
const url = new URL(request.url);
if (url.pathname.endsWith('/videos')) {
- const items = url.searchParams.get('id').split(',').map(id => rawVideos[id] ?? { ...rawVideos.odd, id });
+ const items = url.searchParams.get('id')!.split(',').map(id => (rawVideos as Record<string, unknown>)[id] ?? { ...rawVideos.odd, id });
return reply({ items });
}
const page = playlistPages[url.searchParams.get('pageToken') ?? ''];
diff --git a/backend/tests/utils/scheduler.test.ts b/backend/tests/utils/scheduler.test.ts
index 0ef0591..6116138 100644
--- a/backend/tests/utils/scheduler.test.ts
+++ b/backend/tests/utils/scheduler.test.ts
@@ -2,11 +2,14 @@ import { test, describe, before, after, afterEach, mock } from 'node:test';
import { processScheduledPosts } from '../../utils/scheduler.ts';
import { assertGolden } from '../fixtures/golden.ts';
import { installFetch, reply } from '../fixtures/fakeFetch.ts';
+import type { FetchMock, RecordedRequest } from '../fixtures/fakeFetch.ts';
import { fakeSupabase, accountRow, tableRow } from '../fixtures/fakeSupabase.ts';
+import type { Row } from '../fixtures/fakeSupabase.ts';
+import type { SupabaseClient } from '../../types/app.ts';
const FIXED_NOW = Date.parse('2026-09-01T12:00:00Z');
-function postRow(id, accountId, data, overrides = {}) {
+function postRow(id: string, accountId: string, data: Row, overrides: Row = {}) {
return tableRow('scheduled_posts', { id, user_id: 'user-1', account_id: accountId, status: 'pending', scheduled_at: '2026-09-01T11:00:00.000Z', data, ...overrides });
}
@@ -35,14 +38,14 @@ const ROWS = [
postRow('p-later', 'ig1', { mediaType: 'IMAGE' }, { scheduled_at: '2026-09-02T00:00:00.000Z' }),
];
-const STATUS_SEQUENCES = {
+const STATUS_SEQUENCES: Record<string, string[]> = {
'c-IG1': ['IN_PROGRESS', 'FINISHED'],
'c-ERR': ['ERROR'],
'c-EXP': ['IN_PROGRESS', 'EXPIRED'],
'c-SLOW': [],
};
-function graphReply(request) {
+function graphReply(request: RecordedRequest) {
const url = new URL(request.url);
const parts = url.pathname.split('/');
if (parts[3] === 'media') {
@@ -58,11 +61,11 @@ function graphReply(request) {
return reply({ status_code: statusCode, status: statusCode === 'ERROR' ? 'Bad video' : undefined });
}
-function describeArg(arg) {
+function describeArg(arg: unknown) {
return arg instanceof Error ? `Error: ${arg.message}` : arg;
}
-let fetchMock = null;
+let fetchMock: FetchMock | null = null;
afterEach(() => fetchMock?.restore());
describe('processScheduledPosts golden output', () => {
@@ -72,11 +75,11 @@ describe('processScheduledPosts golden output', () => {
test('publishes due posts, waits for video processing and records failures', async () => {
const supabase = fakeSupabase(ROWS);
fetchMock = installFetch(graphReply);
- const delays = [];
- const logLines = [];
- mock.method(globalThis, 'setTimeout', (callback, ms) => { delays.push(ms); callback(); return 0; });
- mock.method(console, 'log', (...args) => logLines.push(['log', ...args.map(describeArg)]));
- mock.method(console, 'error', (...args) => logLines.push(['error', ...args.map(describeArg)]));
+ const delays: number[] = [];
+ const logLines: unknown[][] = [];
+ mock.method(globalThis, 'setTimeout', (callback: () => void, ms: number) => { delays.push(ms); callback(); return 0; });
+ mock.method(console, 'log', (...args: unknown[]) => logLines.push(['log', ...args.map(describeArg)]));
+ mock.method(console, 'error', (...args: unknown[]) => logLines.push(['error', ...args.map(describeArg)]));
const result = await processScheduledPosts(supabase);
mock.restoreAll();
@@ -85,9 +88,9 @@ describe('processScheduledPosts golden output', () => {
});
test('a failing due post query is logged and nothing is processed', async () => {
- const logLines = [];
- mock.method(console, 'error', (...args) => logLines.push(['error', ...args.map(describeArg)]));
- const result = await processScheduledPosts({ from() { throw new Error('db down'); } });
+ const logLines: unknown[][] = [];
+ mock.method(console, 'error', (...args: unknown[]) => logLines.push(['error', ...args.map(describeArg)]));
+ const result = await processScheduledPosts({ from() { throw new Error('db down'); } } as unknown as SupabaseClient);
mock.restoreAll();
assertGolden({ result, logLines }, 'scheduler.dbFailure');