Skip to content

Commit c3ba738

Browse files
committed
fix vitest 4 mock typings
1 parent 0cfefe6 commit c3ba738

12 files changed

Lines changed: 134 additions & 146 deletions

File tree

packages/cloud/src/__mocks__/vscode.ts

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,30 @@
1-
/* eslint-disable @typescript-eslint/no-explicit-any */
1+
type VscodeWindowMock = {
2+
showInformationMessage: (message: string) => void
3+
showErrorMessage: (message: string) => void
4+
}
5+
6+
type VscodeEnvMock = {
7+
openExternal: (uri: unknown) => Promise<void>
8+
}
9+
10+
type VscodeCommandsMock = {
11+
executeCommand: (command: string, ...args: unknown[]) => Promise<unknown>
12+
}
213

3-
export const window = {
14+
export const window: VscodeWindowMock = {
415
showInformationMessage: vi.fn(),
516
showErrorMessage: vi.fn(),
617
}
718

8-
export const env = {
19+
export const env: VscodeEnvMock = {
920
openExternal: vi.fn(),
1021
}
1122

1223
export const Uri = {
1324
parse: vi.fn((uri: string) => ({ toString: () => uri })),
1425
}
1526

16-
export const commands = {
27+
export const commands: VscodeCommandsMock = {
1728
executeCommand: vi.fn().mockResolvedValue(undefined),
1829
}
1930

@@ -28,9 +39,9 @@ export interface ExtensionContext {
2839
}
2940
globalState: {
3041
get: <T>(key: string) => T | undefined
31-
update: (key: string, value: any) => Promise<void>
42+
update: (key: string, value: unknown) => Promise<void>
3243
}
33-
subscriptions: any[]
44+
subscriptions: unknown[]
3445
extension?: {
3546
packageJSON?: {
3647
version?: string

packages/cloud/src/__tests__/CloudSettingsService.test.ts

Lines changed: 21 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { ExtensionContext } from "vscode"
2+
import type { Mock } from "vitest"
23

34
import type { OrganizationSettings, AuthService } from "@roo-code/types"
45

@@ -13,21 +14,23 @@ vi.mock("../config", () => ({
1314

1415
global.fetch = vi.fn()
1516

17+
type AuthStateChangedListener = (data: unknown) => unknown
18+
1619
describe("CloudSettingsService", () => {
1720
let mockContext: ExtensionContext
1821
let mockAuthService: {
19-
getState: ReturnType<typeof vi.fn>
20-
getSessionToken: ReturnType<typeof vi.fn>
21-
hasActiveSession: ReturnType<typeof vi.fn>
22-
on: ReturnType<typeof vi.fn>
23-
getStoredOrganizationId: ReturnType<typeof vi.fn>
22+
getState: Mock<() => string>
23+
getSessionToken: Mock<() => string | undefined | null>
24+
hasActiveSession: Mock<() => boolean>
25+
on: Mock<(event: string, listener: AuthStateChangedListener) => void>
26+
getStoredOrganizationId: Mock<() => string | null>
2427
}
2528
let mockRefreshTimer: {
26-
start: ReturnType<typeof vi.fn>
27-
stop: ReturnType<typeof vi.fn>
29+
start: Mock<() => void>
30+
stop: Mock<() => void>
2831
}
2932
let cloudSettingsService: CloudSettingsService
30-
let mockLog: ReturnType<typeof vi.fn>
33+
let mockLog: Mock<(...args: unknown[]) => void>
3134

3235
const mockSettings: OrganizationSettings = {
3336
version: 1,
@@ -72,10 +75,12 @@ describe("CloudSettingsService", () => {
7275
stop: vi.fn(),
7376
}
7477

75-
mockLog = vi.fn()
78+
mockLog = vi.fn<(...args: unknown[]) => void>()
7679

7780
// Mock RefreshTimer constructor
78-
vi.mocked(RefreshTimer).mockImplementation(() => mockRefreshTimer as unknown as RefreshTimer)
81+
vi.mocked(RefreshTimer).mockImplementation(function () {
82+
return mockRefreshTimer as unknown as RefreshTimer
83+
})
7984

8085
cloudSettingsService = new CloudSettingsService(mockContext, mockAuthService as unknown as AuthService, mockLog)
8186
})
@@ -502,10 +507,9 @@ describe("CloudSettingsService", () => {
502507
await cloudSettingsService.initialize()
503508

504509
// Get the auth-state-changed handler
505-
const authStateChangedHandler = mockAuthService.on.mock.calls.find(
506-
(call: string[]) => call[0] === "auth-state-changed",
507-
)?.[1]
508-
expect(authStateChangedHandler).toBeDefined()
510+
const [, authStateChangedHandler] = mockAuthService.on.mock.calls.find(
511+
([event]) => event === "auth-state-changed",
512+
) as [string, AuthStateChangedListener]
509513

510514
// Simulate active-session state change
511515
authStateChangedHandler({
@@ -519,10 +523,9 @@ describe("CloudSettingsService", () => {
519523
await cloudSettingsService.initialize()
520524

521525
// Get the auth-state-changed handler
522-
const authStateChangedHandler = mockAuthService.on.mock.calls.find(
523-
(call: string[]) => call[0] === "auth-state-changed",
524-
)?.[1]
525-
expect(authStateChangedHandler).toBeDefined()
526+
const [, authStateChangedHandler] = mockAuthService.on.mock.calls.find(
527+
([event]) => event === "auth-state-changed",
528+
) as [string, AuthStateChangedListener]
526529

527530
// Simulate logged-out state change from active-session
528531
await authStateChangedHandler({

packages/cloud/src/retry-queue/__tests__/RetryQueue.test.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ describe("RetryQueue", () => {
173173

174174
it("should not process retries when paused", async () => {
175175
const fetchMock = vi.fn().mockResolvedValue({ ok: true })
176-
global.fetch = fetchMock
176+
global.fetch = fetchMock as typeof fetch
177177

178178
await retryQueue.enqueue("https://api.example.com/test", { method: "POST" }, "telemetry")
179179

@@ -303,7 +303,7 @@ describe("RetryQueue", () => {
303303
beforeEach(() => {
304304
// Mock global fetch
305305
fetchMock = vi.fn()
306-
global.fetch = fetchMock
306+
global.fetch = fetchMock as typeof fetch
307307
})
308308

309309
afterEach(() => {

packages/config-typescript/vscode-library.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"$schema": "https://json.schemastore.org/tsconfig",
33
"extends": "./base.json",
44
"compilerOptions": {
5-
"types": ["vitest/globals"],
5+
"types": ["node", "vitest/globals"],
66
"outDir": "dist",
77
"module": "esnext",
88
"moduleResolution": "Bundler",

src/core/tools/__tests__/attemptCompletionTool.spec.ts

Lines changed: 35 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1+
import type { Mock } from "vitest"
2+
13
import { RooCodeEventName, TodoItem } from "@roo-code/types"
24

3-
import { AttemptCompletionToolUse } from "../../../shared/tools"
5+
import { AskApproval, AttemptCompletionToolUse, HandleError, PushToolResult } from "../../../shared/tools"
46

57
// Mock the formatResponse module before importing the tool
68
vi.mock("../../prompts/responses", () => ({
@@ -44,28 +46,35 @@ import * as vscode from "vscode"
4446

4547
describe("attemptCompletionTool", () => {
4648
let mockTask: Partial<Task>
47-
let mockPushToolResult: ReturnType<typeof vi.fn>
48-
let mockAskApproval: ReturnType<typeof vi.fn>
49-
let mockHandleError: ReturnType<typeof vi.fn>
50-
let mockToolDescription: ReturnType<typeof vi.fn>
51-
let mockAskFinishSubTaskApproval: ReturnType<typeof vi.fn>
52-
let mockGetConfiguration: ReturnType<typeof vi.fn>
53-
54-
beforeEach(() => {
55-
mockCaptureTaskCompleted.mockReset()
56-
mockPushToolResult = vi.fn()
57-
mockAskApproval = vi.fn()
58-
mockHandleError = vi.fn()
59-
mockToolDescription = vi.fn()
60-
mockAskFinishSubTaskApproval = vi.fn()
61-
mockGetConfiguration = vi.fn(() => ({
62-
get: vi.fn((key: string, defaultValue: any) => {
49+
let mockPushToolResult: Mock<PushToolResult>
50+
let mockAskApproval: Mock<AskApproval>
51+
let mockHandleError: Mock<HandleError>
52+
let mockToolDescription: Mock<() => string>
53+
let mockAskFinishSubTaskApproval: Mock<() => Promise<boolean>>
54+
let mockGetConfiguration: Mock<typeof vscode.workspace.getConfiguration>
55+
const workspaceConfigurationWithOpenTodoCompletionPrevention = (
56+
preventCompletionWithOpenTodos: boolean,
57+
): vscode.WorkspaceConfiguration =>
58+
({
59+
get: <T>(key: string, defaultValue: T): T => {
6360
if (key === "preventCompletionWithOpenTodos") {
64-
return defaultValue // Default to false unless overridden in test
61+
return preventCompletionWithOpenTodos as T
6562
}
63+
6664
return defaultValue
67-
}),
68-
}))
65+
},
66+
}) as vscode.WorkspaceConfiguration
67+
68+
beforeEach(() => {
69+
mockCaptureTaskCompleted.mockReset()
70+
mockPushToolResult = vi.fn<PushToolResult>()
71+
mockAskApproval = vi.fn<AskApproval>()
72+
mockHandleError = vi.fn<HandleError>()
73+
mockToolDescription = vi.fn<() => string>()
74+
mockAskFinishSubTaskApproval = vi.fn<() => Promise<boolean>>()
75+
mockGetConfiguration = vi.fn<typeof vscode.workspace.getConfiguration>(() =>
76+
workspaceConfigurationWithOpenTodoCompletionPrevention(false),
77+
)
6978

7079
// Setup vscode mock
7180
vi.mocked(vscode.workspace.getConfiguration).mockImplementation(mockGetConfiguration)
@@ -182,14 +191,7 @@ describe("attemptCompletionTool", () => {
182191
mockTask.todoList = todosWithPending
183192

184193
// Enable the setting to prevent completion with open todos
185-
mockGetConfiguration.mockReturnValue({
186-
get: vi.fn((key: string, defaultValue: any) => {
187-
if (key === "preventCompletionWithOpenTodos") {
188-
return true // Setting is enabled
189-
}
190-
return defaultValue
191-
}),
192-
})
194+
mockGetConfiguration.mockReturnValue(workspaceConfigurationWithOpenTodoCompletionPrevention(true))
193195

194196
const callbacks: AttemptCompletionCallbacks = {
195197
askApproval: mockAskApproval,
@@ -224,14 +226,7 @@ describe("attemptCompletionTool", () => {
224226
mockTask.todoList = todosWithInProgress
225227

226228
// Enable the setting to prevent completion with open todos
227-
mockGetConfiguration.mockReturnValue({
228-
get: vi.fn((key: string, defaultValue: any) => {
229-
if (key === "preventCompletionWithOpenTodos") {
230-
return true // Setting is enabled
231-
}
232-
return defaultValue
233-
}),
234-
})
229+
mockGetConfiguration.mockReturnValue(workspaceConfigurationWithOpenTodoCompletionPrevention(true))
235230

236231
const callbacks: AttemptCompletionCallbacks = {
237232
askApproval: mockAskApproval,
@@ -267,14 +262,7 @@ describe("attemptCompletionTool", () => {
267262
mockTask.todoList = mixedTodos
268263

269264
// Enable the setting to prevent completion with open todos
270-
mockGetConfiguration.mockReturnValue({
271-
get: vi.fn((key: string, defaultValue: any) => {
272-
if (key === "preventCompletionWithOpenTodos") {
273-
return true // Setting is enabled
274-
}
275-
return defaultValue
276-
}),
277-
})
265+
mockGetConfiguration.mockReturnValue(workspaceConfigurationWithOpenTodoCompletionPrevention(true))
278266

279267
const callbacks: AttemptCompletionCallbacks = {
280268
askApproval: mockAskApproval,
@@ -309,14 +297,7 @@ describe("attemptCompletionTool", () => {
309297
mockTask.todoList = todosWithPending
310298

311299
// Ensure the setting is disabled (default behavior)
312-
mockGetConfiguration.mockReturnValue({
313-
get: vi.fn((key: string, defaultValue: any) => {
314-
if (key === "preventCompletionWithOpenTodos") {
315-
return false // Setting is disabled
316-
}
317-
return defaultValue
318-
}),
319-
})
300+
mockGetConfiguration.mockReturnValue(workspaceConfigurationWithOpenTodoCompletionPrevention(false))
320301

321302
const callbacks: AttemptCompletionCallbacks = {
322303
askApproval: mockAskApproval,
@@ -352,14 +333,7 @@ describe("attemptCompletionTool", () => {
352333
mockTask.todoList = todosWithPending
353334

354335
// Enable the setting
355-
mockGetConfiguration.mockReturnValue({
356-
get: vi.fn((key: string, defaultValue: any) => {
357-
if (key === "preventCompletionWithOpenTodos") {
358-
return true // Setting is enabled
359-
}
360-
return defaultValue
361-
}),
362-
})
336+
mockGetConfiguration.mockReturnValue(workspaceConfigurationWithOpenTodoCompletionPrevention(true))
363337

364338
const callbacks: AttemptCompletionCallbacks = {
365339
askApproval: mockAskApproval,
@@ -395,14 +369,7 @@ describe("attemptCompletionTool", () => {
395369
mockTask.todoList = completedTodos
396370

397371
// Enable the setting
398-
mockGetConfiguration.mockReturnValue({
399-
get: vi.fn((key: string, defaultValue: any) => {
400-
if (key === "preventCompletionWithOpenTodos") {
401-
return true // Setting is enabled
402-
}
403-
return defaultValue
404-
}),
405-
})
372+
mockGetConfiguration.mockReturnValue(workspaceConfigurationWithOpenTodoCompletionPrevention(true))
406373

407374
const callbacks: AttemptCompletionCallbacks = {
408375
askApproval: mockAskApproval,

src/core/tools/__tests__/editFileTool.spec.ts

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
import * as path from "path"
22
import fs from "fs/promises"
33

4-
import type { MockedFunction } from "vitest"
4+
import type { Mock, MockedFunction } from "vitest"
55

66
import { fileExistsAtPath } from "../../../utils/fs"
77
import { isPathOutsideWorkspace } from "../../../utils/pathUtils"
88
import { getReadablePath } from "../../../utils/path"
9-
import { ToolUse, ToolResponse } from "../../../shared/tools"
9+
import { AskApproval, HandleError, PushToolResult, ToolUse, ToolResponse } from "../../../shared/tools"
1010
import { editFileTool } from "../EditFileTool"
1111

1212
vi.mock("fs/promises", () => ({
@@ -88,9 +88,9 @@ describe("editFileTool", () => {
8888
const mockedPathIsAbsolute = path.isAbsolute as MockedFunction<typeof path.isAbsolute>
8989

9090
const mockTask: any = {}
91-
let mockAskApproval: ReturnType<typeof vi.fn>
92-
let mockHandleError: ReturnType<typeof vi.fn>
93-
let mockPushToolResult: ReturnType<typeof vi.fn>
91+
let mockAskApproval: Mock<AskApproval>
92+
let mockHandleError: Mock<HandleError>
93+
let mockPushToolResult: Mock<PushToolResult>
9494
let toolResult: ToolResponse | undefined
9595

9696
beforeEach(() => {
@@ -150,8 +150,8 @@ describe("editFileTool", () => {
150150
mockTask.processQueuedMessages = vi.fn()
151151
mockTask.sayAndCreateMissingParamError = vi.fn().mockResolvedValue("Missing param error")
152152

153-
mockAskApproval = vi.fn().mockResolvedValue(true)
154-
mockHandleError = vi.fn().mockResolvedValue(undefined)
153+
mockAskApproval = vi.fn<AskApproval>().mockResolvedValue(true)
154+
mockHandleError = vi.fn<HandleError>().mockResolvedValue(undefined)
155155

156156
toolResult = undefined
157157
})
@@ -203,7 +203,7 @@ describe("editFileTool", () => {
203203
partial: isPartial,
204204
}
205205

206-
mockPushToolResult = vi.fn((result: ToolResponse) => {
206+
mockPushToolResult = vi.fn<PushToolResult>((result) => {
207207
toolResult = result
208208
})
209209

@@ -280,7 +280,7 @@ describe("editFileTool", () => {
280280
}
281281

282282
let capturedResult: ToolResponse | undefined
283-
const localPushToolResult = vi.fn((result: ToolResponse) => {
283+
const localPushToolResult = vi.fn<PushToolResult>((result) => {
284284
capturedResult = result
285285
})
286286

@@ -649,7 +649,7 @@ describe("editFileTool", () => {
649649
}
650650

651651
let capturedResult: ToolResponse | undefined
652-
const localPushToolResult = vi.fn((result: ToolResponse) => {
652+
const localPushToolResult = vi.fn<PushToolResult>((result) => {
653653
capturedResult = result
654654
})
655655

0 commit comments

Comments
 (0)