chore: Fix types in tests 36/N.

This commit is contained in:
cpojer
2026-02-17 15:46:48 +09:00
parent 2a4ca7671e
commit 7b31e8fc59
14 changed files with 86 additions and 42 deletions

View File

@@ -26,8 +26,8 @@ describe("voyage embedding provider", () => {
});
it("configures client with correct defaults and headers", async () => {
const fetchMock = createFetchMock();
vi.stubGlobal("fetch", fetchMock);
const fetchMock = createFetchMock() as ReturnType<typeof vi.fn>;
vi.stubGlobal("fetch", fetchMock as unknown as typeof fetch);
vi.mocked(authModule.resolveApiKeyForProvider).mockResolvedValue({
apiKey: "voyage-key-123",
@@ -64,8 +64,8 @@ describe("voyage embedding provider", () => {
});
it("respects remote overrides for baseUrl and apiKey", async () => {
const fetchMock = createFetchMock();
vi.stubGlobal("fetch", fetchMock);
const fetchMock = createFetchMock() as ReturnType<typeof vi.fn>;
vi.stubGlobal("fetch", fetchMock as unknown as typeof fetch);
const result = await createVoyageEmbeddingProvider({
config: {} as never,
@@ -96,8 +96,8 @@ describe("voyage embedding provider", () => {
json: async () => ({
data: [{ embedding: [0.1, 0.2] }, { embedding: [0.3, 0.4] }],
}),
})) as unknown as typeof fetch;
vi.stubGlobal("fetch", fetchMock);
})) as ReturnType<typeof vi.fn>;
vi.stubGlobal("fetch", fetchMock as unknown as typeof fetch);
vi.mocked(authModule.resolveApiKeyForProvider).mockResolvedValue({
apiKey: "voyage-key-123",

View File

@@ -2,6 +2,7 @@ import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { OpenClawConfig } from "../config/config.js";
import { getMemorySearchManager, type MemoryIndexManager } from "./index.js";
import { createOpenAIEmbeddingProviderMock } from "./test-embeddings-mock.js";
@@ -53,21 +54,25 @@ describe("memory search async sync", () => {
},
list: [{ id: "main", default: true }],
},
};
} as OpenClawConfig;
const result = await getMemorySearchManager({ cfg, agentId: "main" });
expect(result.manager).not.toBeNull();
if (!result.manager) {
throw new Error("manager missing");
}
manager = result.manager;
manager = result.manager as unknown as MemoryIndexManager;
const pending = new Promise<void>(() => {});
(manager as unknown as { sync: () => Promise<void> }).sync = vi.fn(async () => pending);
const resolved = await new Promise<boolean>((resolve, reject) => {
const timeout = setTimeout(() => resolve(false), 1000);
void manager
const activeManager = manager;
if (!activeManager) {
throw new Error("manager missing");
}
void activeManager
.search("hello")
.then(() => {
clearTimeout(timeout);

View File

@@ -2,6 +2,7 @@ import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import type { OpenClawConfig } from "../config/config.js";
import { getEmbedBatchMock, resetEmbeddingMocks } from "./embedding.test-mocks.js";
import type { MemoryIndexManager } from "./index.js";
import { getRequiredMemoryIndexManager } from "./test-manager-helpers.js";
@@ -68,7 +69,7 @@ describe("memory manager atomic reindex", () => {
},
list: [{ id: "main", default: true }],
},
};
} as OpenClawConfig;
manager = await getRequiredMemoryIndexManager({ cfg, agentId: "main" });

View File

@@ -2,11 +2,12 @@ import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import type { OpenClawConfig } from "../config/config.js";
import { getMemorySearchManager, type MemoryIndexManager } from "./index.js";
import { createOpenAIEmbeddingProviderMock } from "./test-embeddings-mock.js";
import "./test-runtime-mocks.js";
const embedBatch = vi.fn(async () => []);
const embedBatch = vi.fn(async (_texts: string[]) => [] as number[][]);
const embedQuery = vi.fn(async () => [0.5, 0.5, 0.5]);
vi.mock("./embeddings.js", () => ({
@@ -110,7 +111,7 @@ describe("memory indexing with OpenAI batches", () => {
return { fetchMock, state };
}
function createBatchCfg() {
function createBatchCfg(): OpenClawConfig {
return {
agents: {
defaults: {
@@ -126,7 +127,7 @@ describe("memory indexing with OpenAI batches", () => {
},
list: [{ id: "main", default: true }],
},
};
} as OpenClawConfig;
}
beforeAll(async () => {
@@ -141,7 +142,7 @@ describe("memory indexing with OpenAI batches", () => {
if (!result.manager) {
throw new Error("manager missing");
}
manager = result.manager;
manager = result.manager as unknown as MemoryIndexManager;
});
afterAll(async () => {

View File

@@ -43,7 +43,10 @@ describe("memory embedding batches", () => {
});
const status = managerLarge.status();
const totalTexts = embedBatch.mock.calls.reduce((sum, call) => sum + (call[0]?.length ?? 0), 0);
const totalTexts = embedBatch.mock.calls.reduce(
(sum: number, call: unknown[]) => sum + ((call[0] as string[] | undefined)?.length ?? 0),
0,
);
expect(totalTexts).toBe(status.chunks);
expect(embedBatch.mock.calls.length).toBeGreaterThan(1);
expect(updates.length).toBeGreaterThan(0);
@@ -112,7 +115,7 @@ describe("memory embedding batches", () => {
await fs.writeFile(path.join(memoryDir, "2026-01-07.md"), "\n\n\n");
await managerSmall.sync({ reason: "test" });
const inputs = embedBatch.mock.calls.flatMap((call) => call[0] ?? []);
const inputs = embedBatch.mock.calls.flatMap((call: unknown[]) => (call[0] as string[]) ?? []);
expect(inputs).not.toContain("");
});
});

View File

@@ -2,6 +2,7 @@ import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { OpenClawConfig } from "../config/config.js";
import { getEmbedBatchMock, resetEmbeddingMocks } from "./embedding.test-mocks.js";
import type { MemoryIndexManager } from "./index.js";
import { getRequiredMemoryIndexManager } from "./test-manager-helpers.js";
@@ -53,7 +54,7 @@ describe("memory manager sync failures", () => {
},
list: [{ id: "main", default: true }],
},
};
} as OpenClawConfig;
manager = await getRequiredMemoryIndexManager({ cfg, agentId: "main" });
const syncSpy = vi.spyOn(manager, "sync");

View File

@@ -2,6 +2,7 @@ import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { OpenClawConfig } from "../config/config.js";
import { getMemorySearchManager, type MemoryIndexManager } from "./index.js";
import { buildFileEntry } from "./internal.js";
@@ -54,14 +55,14 @@ describe("memory vector dedupe", () => {
},
list: [{ id: "main", default: true }],
},
};
} as OpenClawConfig;
const result = await getMemorySearchManager({ cfg, agentId: "main" });
expect(result.manager).not.toBeNull();
if (!result.manager) {
throw new Error("manager missing");
}
manager = result.manager;
manager = result.manager as unknown as MemoryIndexManager;
const db = (
manager as unknown as {

View File

@@ -2,6 +2,7 @@ import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { OpenClawConfig } from "../config/config.js";
import { getMemorySearchManager, type MemoryIndexManager } from "./index.js";
const { watchMock } = vi.hoisted(() => ({
@@ -72,14 +73,14 @@ describe("memory watcher config", () => {
},
list: [{ id: "main", default: true }],
},
};
} as OpenClawConfig;
const result = await getMemorySearchManager({ cfg, agentId: "main" });
expect(result.manager).not.toBeNull();
if (!result.manager) {
throw new Error("manager missing");
}
manager = result.manager;
manager = result.manager as unknown as MemoryIndexManager;
expect(watchMock).toHaveBeenCalledTimes(1);
const [watchedPaths, options] = watchMock.mock.calls[0] as unknown as [

View File

@@ -98,7 +98,11 @@ describe("pairing store", () => {
it("regenerates when a generated code collides", async () => {
await withTempStateDir(async () => {
const spy = vi.spyOn(crypto, "randomInt");
const spy = vi.spyOn(crypto, "randomInt") as unknown as {
mockReturnValue: (value: number) => void;
mockImplementation: (fn: () => number) => void;
mockRestore: () => void;
};
try {
spy.mockReturnValue(0);
const first = await upsertChannelPairingRequest({

View File

@@ -8,7 +8,7 @@
import { beforeEach, describe, expect, it } from "vitest";
import { createHookRunner } from "./hooks.js";
import { createEmptyPluginRegistry, type PluginRegistry } from "./registry.js";
import type { PluginHookBeforeAgentStartResult, TypedPluginHookRegistration } from "./types.js";
import type { PluginHookBeforeAgentStartResult, PluginHookRegistration } from "./types.js";
function addBeforeAgentStartHook(
registry: PluginRegistry,
@@ -22,7 +22,7 @@ function addBeforeAgentStartHook(
handler,
priority,
source: "test",
} as TypedPluginHookRegistration);
} as PluginHookRegistration);
}
const stubCtx = {

View File

@@ -16,7 +16,7 @@ import type {
PluginHookBeforeModelResolveResult,
PluginHookBeforePromptBuildEvent,
PluginHookBeforePromptBuildResult,
TypedPluginHookRegistration,
PluginHookRegistration,
} from "./types.js";
function addBeforeModelResolveHook(
@@ -34,7 +34,7 @@ function addBeforeModelResolveHook(
handler,
priority,
source: "test",
} as TypedPluginHookRegistration);
} as PluginHookRegistration);
}
function addBeforePromptBuildHook(
@@ -52,7 +52,7 @@ function addBeforePromptBuildHook(
handler,
priority,
source: "test",
} as TypedPluginHookRegistration);
} as PluginHookRegistration);
}
function addLegacyBeforeAgentStartHook(
@@ -67,7 +67,7 @@ function addLegacyBeforeAgentStartHook(
handler,
priority,
source: "test",
} as TypedPluginHookRegistration);
} as PluginHookRegistration);
}
const stubCtx: PluginHookAgentContext = {

View File

@@ -4,7 +4,7 @@ import { createEmptyPluginRegistry, type PluginRegistry } from "./registry.js";
import type {
PluginHookBeforeModelResolveResult,
PluginHookBeforePromptBuildResult,
TypedPluginHookRegistration,
PluginHookRegistration,
} from "./types.js";
function addTypedHook(
@@ -23,7 +23,7 @@ function addTypedHook(
handler,
priority,
source: "test",
} as TypedPluginHookRegistration);
} as PluginHookRegistration);
}
describe("phase hooks merger", () => {

View File

@@ -423,7 +423,14 @@ describe("installPluginFromDir", () => {
const { runCommandWithTimeout } = await import("../process/exec.js");
const run = vi.mocked(runCommandWithTimeout);
run.mockResolvedValue({ code: 0, stdout: "", stderr: "" });
run.mockResolvedValue({
code: 0,
stdout: "",
stderr: "",
signal: null,
killed: false,
termination: "exit",
});
const { installPluginFromDir } = await import("./install.js");
const res = await installPluginFromDir({
@@ -468,9 +475,16 @@ describe("installPluginFromNpmSpec", () => {
const packedName = "voice-call-0.0.1.tgz";
run.mockImplementation(async (argv, opts) => {
if (argv[0] === "npm" && argv[1] === "pack") {
packTmpDir = String(opts?.cwd ?? "");
packTmpDir = String(typeof opts === "number" ? "" : (opts.cwd ?? ""));
await packToArchive({ pkgDir, outDir: packTmpDir, outName: packedName });
return { code: 0, stdout: `${packedName}\n`, stderr: "", signal: null, killed: false };
return {
code: 0,
stdout: `${packedName}\n`,
stderr: "",
signal: null,
killed: false,
termination: "exit",
};
}
throw new Error(`unexpected command: ${argv.join(" ")}`);
});
@@ -493,7 +507,8 @@ describe("installPluginFromNpmSpec", () => {
}
const [argv, options] = packCall;
expect(argv).toEqual(["npm", "pack", "@openclaw/voice-call@0.0.1", "--ignore-scripts"]);
expect(options?.env).toMatchObject({ NPM_CONFIG_IGNORE_SCRIPTS: "true" });
const commandOptions = typeof options === "number" ? undefined : options;
expect(commandOptions?.env).toMatchObject({ NPM_CONFIG_IGNORE_SCRIPTS: "true" });
expect(packTmpDir).not.toBe("");
expect(fs.existsSync(packTmpDir)).toBe(false);

View File

@@ -28,12 +28,12 @@ const noopLogger = {
};
type Registered = {
methods: Map<string, (ctx: Record<string, unknown>) => unknown>;
methods: Map<string, unknown>;
tools: unknown[];
};
function setup(config: Record<string, unknown>): Registered {
const methods = new Map<string, (ctx: Record<string, unknown>) => unknown>();
const methods = new Map<string, unknown>();
const tools: unknown[] = [];
plugin.register({
id: "voice-call",
@@ -43,14 +43,16 @@ function setup(config: Record<string, unknown>): Registered {
source: "test",
config: {},
pluginConfig: config,
runtime: { tts: { textToSpeechTelephony: vi.fn() } },
runtime: { tts: { textToSpeechTelephony: vi.fn() } } as unknown as Parameters<
typeof plugin.register
>[0]["runtime"],
logger: noopLogger,
registerGatewayMethod: (method, handler) => methods.set(method, handler),
registerTool: (tool) => tools.push(tool),
registerGatewayMethod: (method: string, handler: unknown) => methods.set(method, handler),
registerTool: (tool: unknown) => tools.push(tool),
registerCli: () => {},
registerService: () => {},
resolvePath: (p: string) => p,
});
} as unknown as Parameters<typeof plugin.register>[0]);
return { methods, tools };
}
@@ -87,7 +89,12 @@ describe("voice-call plugin", () => {
it("initiates a call via voicecall.initiate", async () => {
const { methods } = setup({ provider: "mock" });
const handler = methods.get("voicecall.initiate");
const handler = methods.get("voicecall.initiate") as
| ((ctx: {
params: Record<string, unknown>;
respond: ReturnType<typeof vi.fn>;
}) => Promise<void>)
| undefined;
const respond = vi.fn();
await handler?.({ params: { message: "Hi" }, respond });
expect(runtimeStub.manager.initiateCall).toHaveBeenCalled();
@@ -98,7 +105,12 @@ describe("voice-call plugin", () => {
it("returns call status", async () => {
const { methods } = setup({ provider: "mock" });
const handler = methods.get("voicecall.status");
const handler = methods.get("voicecall.status") as
| ((ctx: {
params: Record<string, unknown>;
respond: ReturnType<typeof vi.fn>;
}) => Promise<void>)
| undefined;
const respond = vi.fn();
await handler?.({ params: { callId: "call-1" }, respond });
const [ok, payload] = respond.mock.calls[0];