Open source CapCut alternative.
TypeScript
fix(site): restore module stubs after each test file
David Le58dbdb2ae5d7
diff --git a/site/src/cut/lib/audioMixCross.test.ts b/site/src/cut/lib/audioMixCross.test.tsindex 7d5a6e8d..3590a615 100644--- a/site/src/cut/lib/audioMixCross.test.ts+++ b/site/src/cut/lib/audioMixCross.test.ts@@ -1,4 +1,5 @@-import { describe, expect, mock, test } from "bun:test";+import { describe, expect, test } from "bun:test";+import { stubModule } from "@/lib/testing/stubModule";import { AudioBuffer, OfflineAudioContext } from "node-web-audio-api";// The offline fold's side of a cross dissolve, on the Web Audio the headless@@ -22,10 +23,10 @@ const tone = (seconds: number, hz: number) => {return buf;};-mock.module("./mediaRead", () => ({- decodeAudioSpan: async (file: string, from: number, to: number) =>- tone(to - from, file === "a.mp4" ? 440 : 880),-}));+await stubModule<typeof import("./mediaRead")>("./mediaRead", import.meta.url, {+ decodeAudioSpan: (async (file: string, from: number, to: number) =>+ tone(to - from, file === "a.mp4" ? 440 : 880)) as never,+});const { renderMix } = await import("./audioMix");diff --git a/site/src/cut/lib/audioMixFx.test.ts b/site/src/cut/lib/audioMixFx.test.tsindex 7edb75df..8a16c6bb 100644--- a/site/src/cut/lib/audioMixFx.test.ts+++ b/site/src/cut/lib/audioMixFx.test.ts@@ -1,4 +1,5 @@-import { describe, expect, mock, test } from "bun:test";+import { describe, expect, test } from "bun:test";+import { stubModule } from "@/lib/testing/stubModule";import { AudioBuffer, OfflineAudioContext } from "node-web-audio-api";// The fold runs on Web Audio, which Node has through the same package the@@ -26,7 +27,7 @@ const tone = () => {return buf;};-mock.module("./mediaRead", () => ({ decodeAudioSpan: async () => tone() }));+await stubModule<typeof import("./mediaRead")>("./mediaRead", import.meta.url, { decodeAudioSpan: async () => tone() });const { renderMix } = await import("./audioMix");diff --git a/site/src/cut/lib/chunkAdopt.test.ts b/site/src/cut/lib/chunkAdopt.test.tsindex f01c175f..868c9ee1 100644--- a/site/src/cut/lib/chunkAdopt.test.ts+++ b/site/src/cut/lib/chunkAdopt.test.ts@@ -1,4 +1,5 @@-import { describe, expect, mock, test } from "bun:test";+import { describe, expect, test } from "bun:test";+import { stubModule } from "@/lib/testing/stubModule";/*** The byte cache carried across an import's landing.@@ -65,26 +66,24 @@ class FakeDir {let root = new FakeDir();-const opfs = await import("./backend/browser/opfs");-mock.module("./backend/browser/opfs", () => ({- ...opfs,+await stubModule<typeof import("./backend/browser/opfs")>("./backend/browser/opfs", import.meta.url, {supportsBrowserStore: () => true,chunksDir: async () => root as never,// The real readers over the fake handles.- readFileAt: async (dir: FakeDir | null, name: string) => {+ readFileAt: (async (dir: FakeDir | null, name: string) => {if (!dir) return null;try {return await (await dir.getFileHandle(name)).getFile();} catch {return null;}- },- writeFileAt: async (dir: FakeDir, name: string, data: Blob | ArrayBuffer | string) => {+ }) as never,+ writeFileAt: (async (dir: FakeDir, name: string, data: Blob | ArrayBuffer | string) => {const w = await (await dir.getFileHandle(name, { create: true })).createWritable();await w.write(data);await w.close();- },- readJson: async (dir: FakeDir | null, name: string) => {+ }) as never,+ readJson: (async (dir: FakeDir | null, name: string) => {if (!dir) return null;try {const file = await (await dir.getFileHandle(name)).getFile();@@ -92,8 +91,8 @@ mock.module("./backend/browser/opfs", () => ({} catch {return null;}- },-}));+ }) as never,+});const { CHUNK_SIZE, adoptChunks, chunkIdentity, encodeResident, decodeResident } = await import("./chunkCache"diff --git a/site/src/cut/lib/compareToSource.test.ts b/site/src/cut/lib/compareToSource.test.tsindex 66d1b527..fe0195a3 100644--- a/site/src/cut/lib/compareToSource.test.ts+++ b/site/src/cut/lib/compareToSource.test.ts@@ -1,4 +1,5 @@-import { beforeEach, expect, mock, test } from "bun:test";+import { beforeEach, expect, test } from "bun:test";+import { stubModule } from "@/lib/testing/stubModule";import { setRasterFactory, type RasterSurface } from "./raster";import { useEditor } from "./store";@@ -36,8 +37,6 @@ setRasterFactory({// it accepts is worth pinning: the moments it is given, the ones it turns away// before drawing anything, and the shape of the read it makes of the source.-const media = await import("./mediaRead");-/** Every time the source was asked for frames, and at what size. */const reads: { times: number[]; size: unknown }[] = [];@@ -46,7 +45,7 @@ async function* framesAt(_src: string | Blob, times: number[], size?: unknown) {for (let i = 0; i < times.length; i++) yield { canvas: stubCanvas(90, 160), timestamp: 0, duration: 0 } as never;}-mock.module("./mediaRead", () => ({ ...media, framesAt }));+await stubModule<typeof import("./mediaRead")>("./mediaRead", import.meta.url, { framesAt });const { runAiTool } = await import("./aiTools");diff --git a/site/src/cut/lib/frameSource.test.ts b/site/src/cut/lib/frameSource.test.tsindex fec64fe6..2a399ed5 100644--- a/site/src/cut/lib/frameSource.test.ts+++ b/site/src/cut/lib/frameSource.test.ts@@ -1,12 +1,11 @@-import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";+import { afterEach, beforeEach, describe, expect, test } from "bun:test";import { retimeOf } from "@donkeycut/effects-kit";+import { stubModule } from "@/lib/testing/stubModule";import { DECODE_AHEAD_S, type Timed } from "./frameSource";import type { MediaAsset } from "./types";// ── the files a source reads, stood in for ──────────────────────────────────-// Only the reads are replaced; the module mock spreads the real module, so-// every other export is carried through as it is (and other test files in the-// run see the real behavior for everything but these).+// Only the reads are replaced; every other export is carried through as it is.interface FakeInput {url: string;@@ -82,7 +81,6 @@ const frameSink = ((track: FakeTrack, size?: { height?: number }) => ({})) as never;const keyframeTimeAt = (async (_track: unknown, t: number) => Math.max(0, Math.floor(t))) as never;-const media = await import("./mediaRead");// The shared open, over the fake files: one input per URL, closed by the// last holder to let go, the way the real one is.const shared = new Map<string, { input: FakeInput; refs: number }>();@@ -106,14 +104,13 @@ const openMediaShared = (src: string) => {},};};-mock.module("./mediaRead", () => ({- ...media,+await stubModule<typeof import("./mediaRead")>("./mediaRead", import.meta.url, {openMedia,- openMediaShared,+ openMediaShared: openMediaShared as never,videoTrackOf,frameSink,keyframeTimeAt,-}));+});const { BACK_WINDOW, ClipFrameSource, FrameRing, FrameSourcePool, mappingKey, walkClaim } =await import("./frameSource");diff --git a/site/src/cut/lib/previewMixer.test.ts b/site/src/cut/lib/previewMixer.test.tsindex f0afea8d..b969e3b2 100644--- a/site/src/cut/lib/previewMixer.test.ts+++ b/site/src/cut/lib/previewMixer.test.ts@@ -1,4 +1,5 @@-import { describe, expect, mock, test } from "bun:test";+import { describe, expect, test } from "bun:test";+import { stubModule } from "@/lib/testing/stubModule";import { retimeOf } from "@donkeycut/effects-kit";import { AudioBuffer } from "node-web-audio-api";@@ -217,18 +218,18 @@ const decodeAudioSpan = async (_url: string, from: number, to: number) => {});};-// Only the reads are stood in for. A module mock replaces the whole module for-// every test file in the run, so the rest of each one is carried through as it-// really is.-const media = await import("./mediaRead");-const links = await import("./mediaLinks");-mock.module("./mediaRead", () => ({ ...media, openAudioWalk, assembleAudio, decodeAudioSpan }));-mock.module("./mediaLinks", () => ({- ...links,+// Only the reads are stood in for; the rest of each module is carried through+// as it really is.+await stubModule<typeof import("./mediaRead")>("./mediaRead", import.meta.url, {+ openAudioWalk: openAudioWalk as never,+ assembleAudio,+ decodeAudioSpan: decodeAudioSpan as never,+});+await stubModule<typeof import("./mediaLinks")>("./mediaLinks", import.meta.url, {reportMediaUrlError: () => {reMints.asked++;},-}));+});const { PreviewMixer } = await import("./previewMixer");diff --git a/site/src/cut/server/cloud/commands.test.ts b/site/src/cut/server/cloud/commands.test.tsindex 95201692..538a4ceb 100644--- a/site/src/cut/server/cloud/commands.test.ts+++ b/site/src/cut/server/cloud/commands.test.ts@@ -1,5 +1,5 @@import { afterAll, beforeEach, expect, mock, test } from "bun:test";-import { prisma as actualPrisma } from "@/lib/prisma";+import { stubModule } from "@/lib/testing/stubModule";// The commands module reaches the database through the shared client; this// stand-in keeps job rows in memory and answers the handful of calls the@@ -51,7 +51,7 @@ const prisma = {user: { findUnique: mock(async () => ({ superUser: true })) },settingOverride: { findUnique: mock(async () => null) },};-mock.module("@/lib/prisma", () => ({ prisma }));+await stubModule<typeof import("@/lib/prisma")>("@/lib/prisma", import.meta.url, { prisma: prisma as never });// The wake is a POST to the worker; count those instead of the network.process.env.CUT_RENDER_WAKE_SECRET = "test-wake";const realFetch = globalThis.fetch;@@ -60,7 +60,7 @@ globalThis.fetch = (async (url: string | URL | Request, init?: RequestInit) => {return realFetch(url, init);}) as typeof fetch;const { claimEditorBatch, CLAIM_QUIET_MS, heartbeatEditorBatch, NO_CARD_OPEN, queueCommands, settleEditorBatch, waitForJob } = await import("./commands");-afterAll(() => { mock.module("@/lib/prisma", () => ({ prisma: actualPrisma })); globalThis.fetch = realFetch; });+afterAll(() => { globalThis.fetch = realFetch; });beforeEach(() => { rows.splice(0); woken.count = 0; });test("batches queue behind each other for the card without waking the worker, and the card claims them oldest first", async () => {diff --git a/site/src/cut/worker/db.test.ts b/site/src/cut/worker/db.test.tsindex 25c13593..3ae885b3 100644--- a/site/src/cut/worker/db.test.ts+++ b/site/src/cut/worker/db.test.ts@@ -1,8 +1,7 @@-import { afterAll, afterEach, expect, mock, test } from "bun:test";+import { afterEach, expect, mock, test } from "bun:test";import { Prisma } from "@/generated/prisma/client";-import { prisma as actualPrisma } from "@/lib/prisma";+import { stubModule } from "@/lib/testing/stubModule";-const originalPrisma = actualPrisma;// The account the charge point weighs every object against: free tier, no Pro.const prisma = {settingOverride: { findUnique: mock(async () => ({ value: { maxAttempts: 3 } })) },@@ -15,11 +14,10 @@ const prisma = {void run; void options;throw new Error("Unexpected transaction");}) };-mock.module("@/lib/prisma", () => ({ prisma }));+await stubModule<typeof import("@/lib/prisma")>("@/lib/prisma", import.meta.url, { prisma: prisma as never });const { registerObject, unregisterObjects } = await import("./db");const { FREE_STORAGE_BYTES } = await import("../server/cloud/limits");const { STORAGE_FULL } = await import("../lib/operationFailure");-afterAll(() => { mock.module("@/lib/prisma", () => ({ prisma: originalPrisma })); });const conflict = () => new Prisma.PrismaClientKnownRequestError("Write conflict", {code: "P2034", clientVersion: "test",diff --git a/site/src/lib/testing/stubModule.ts b/site/src/lib/testing/stubModule.tsnew file mode 100644index 00000000..ab2a20c0--- /dev/null+++ b/site/src/lib/testing/stubModule.ts@@ -0,0 +1,29 @@+import { afterAll, mock } from "bun:test";+import { dirname } from "node:path";+import { fileURLToPath } from "node:url";++declare const Bun: { resolveSync(specifier: string, from: string): string };++/**+ * Stand in for some of a module's exports for the test file that calls this.+ *+ * Bun runs every test file in one process, and a module mock rewrites the+ * loaded module for every file that runs after it, so the order the files+ * run in on one machine decides what another machine's suite reads. The+ * originals are copied before the mock goes in and put back once this file's+ * tests are done. `from` is the caller's `import.meta.url`; the specifier+ * resolves against it the way an import from that file would.+ */+export async function stubModule<T extends object>(+ specifier: string,+ from: string,+ overrides: Partial<T>,+): Promise<T> {+ const path = Bun.resolveSync(specifier, dirname(fileURLToPath(from)));+ const real = { ...((await import(path)) as T) };+ mock.module(path, () => ({ ...real, ...overrides }));+ afterAll(() => {+ mock.module(path, () => real);+ });+ return real;+}