Skip to content

Commit 4291a59

Browse files
fix: add missing vi.mock() calls to prevent vitest worker shutdown flakiness (calcom#28459)
* fix: add missing vi.mock() calls to prevent vitest worker shutdown flakiness Add vi.mock() calls for modules that trigger background network requests or database connections during import. These transitive imports can cause the vitest worker RPC to shut down while pending fetch/network operations are still in flight, resulting in flaky test failures with: Error: [vitest-worker]: Closing rpc while "fetch" was pending The primary modules mocked are: - @calcom/app-store/delegationCredential (triggers credential lookups) - @calcom/prisma (triggers database initialization) - @calcom/features/calendars/lib/CalendarManager (triggers calendar API calls) - @calcom/features/auth/lib/verifyEmail (triggers email service) - @calcom/lib/domainManager/organization (triggers domain lookups) Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix: remove conflicting empty prisma mocks from files with prismock/prismaMock setups - Remove vi.mock('@calcom/prisma', () => ({ default: {}, prisma: {} })) from 28 files that already have prismock/prismaMock test doubles. Vitest hoists all vi.mock() calls and the last one wins, so these empty mocks were overriding the functional test doubles. - Fix CalendarSubscriptionService.test.ts to reuse the shared mock from __mocks__/delegationCredential instead of creating a new unconfigured vi.fn() - Remove DelegationCredentialRepository.test.ts empty prisma mock (different pattern) - Remove vi.mock from inside beforeEach in intentToCreateOrg.handler.test.ts Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix: add comprehensive delegationCredential mock exports to prevent CI test failures The vi.mock blocks for @calcom/app-store/delegationCredential were missing exports that the code under test transitively imports (e.g. enrichUsersWithDelegationCredentials, enrichUserWithDelegationCredentialsIncludeServiceAccountKey, buildAllCredentials, getFirstDelegationConferencingCredentialAppLocation). Added all exports with passthrough implementations so the booking flow works correctly without triggering real network requests. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix: correct credential mock return shapes to match real module API Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix: revert unintended yarn.lock changes Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
1 parent 353f71b commit 4291a59

70 files changed

Lines changed: 557 additions & 267 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

apps/api/v1/lib/helpers/rateLimitApiKey.test.ts

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
1-
import type { RatelimitResponse } from "@unkey/ratelimit";
2-
import type { Request, Response } from "express";
3-
import type { NextApiResponse, NextApiRequest } from "next";
4-
import { createMocks } from "node-mocks-http";
5-
import { describe, it, expect, vi } from "vitest";
6-
71
import { handleAutoLock } from "@calcom/features/ee/api-keys/lib/autoLock";
82
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
93
import { HttpError } from "@calcom/lib/http-error";
10-
4+
import type { RatelimitResponse } from "@unkey/ratelimit";
5+
import type { Request, Response } from "express";
6+
import type { NextApiRequest, NextApiResponse } from "next";
7+
import { createMocks } from "node-mocks-http";
8+
import { describe, expect, it, vi } from "vitest";
119
import { rateLimitApiKey } from "~/lib/helpers/rateLimitApiKey";
1210

1311
type CustomNextApiRequest = NextApiRequest & Request;
@@ -23,6 +21,11 @@ vi.mock("@calcom/features/ee/api-keys/lib/autoLock", () => ({
2321
handleAutoLock: vi.fn(),
2422
}));
2523

24+
vi.mock("@calcom/prisma", () => ({
25+
default: {},
26+
prisma: {},
27+
}));
28+
2629
describe("rateLimitApiKey middleware", () => {
2730
it("should return 401 if no apiKey is provided", async () => {
2831
const { req, res } = createMocks<CustomNextApiRequest, CustomNextApiResponse>({

apps/api/v1/test/lib/bookings/[id]/recordings/_get.test.ts

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,14 @@
11
import prismaMock from "@calcom/testing/lib/__mocks__/prismaMock";
2-
3-
import type { Request, Response } from "express";
4-
import type { NextApiRequest, NextApiResponse } from "next";
5-
import { createMocks } from "node-mocks-http";
6-
import { describe, expect, test, vi, afterEach } from "vitest";
7-
82
import {
9-
getRecordingsOfCalVideoByRoomName,
103
getDownloadLinkOfCalVideoByRecordingId,
4+
getRecordingsOfCalVideoByRoomName,
115
} from "@calcom/features/conferencing/lib/videoClient";
126
import { buildBooking } from "@calcom/lib/test/builder";
13-
7+
import type { Request, Response } from "express";
8+
import type { NextApiRequest, NextApiResponse } from "next";
9+
import { createMocks } from "node-mocks-http";
10+
import { afterEach, describe, expect, test, vi } from "vitest";
1411
import { getAccessibleUsers } from "~/lib/utils/retrieveScopedAccessibleUsers";
15-
1612
import authMiddleware from "../../../../../pages/api/bookings/[id]/_auth-middleware";
1713
import handler from "../../../../../pages/api/bookings/[id]/recordings/_get";
1814

@@ -34,7 +30,6 @@ vi.mock("~/lib/utils/retrieveScopedAccessibleUsers", () => {
3430
getAccessibleUsers: vi.fn(),
3531
};
3632
});
37-
3833
afterEach(() => {
3934
vi.resetAllMocks();
4035
});

apps/api/v1/test/lib/bookings/[id]/transcripts/[recordingId]/_get.test.ts

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,14 @@
11
import prismaMock from "@calcom/testing/lib/__mocks__/prismaMock";
2-
3-
import type { Request, Response } from "express";
4-
import type { NextApiRequest, NextApiResponse } from "next";
5-
import { createMocks } from "node-mocks-http";
6-
import { describe, expect, test, vi, afterEach } from "vitest";
7-
82
import {
9-
getTranscriptsAccessLinkFromRecordingId,
103
checkIfRoomNameMatchesInRecording,
4+
getTranscriptsAccessLinkFromRecordingId,
115
} from "@calcom/features/conferencing/lib/videoClient";
126
import { buildBooking } from "@calcom/lib/test/builder";
13-
7+
import type { Request, Response } from "express";
8+
import type { NextApiRequest, NextApiResponse } from "next";
9+
import { createMocks } from "node-mocks-http";
10+
import { afterEach, describe, expect, test, vi } from "vitest";
1411
import { getAccessibleUsers } from "~/lib/utils/retrieveScopedAccessibleUsers";
15-
1612
import authMiddleware from "../../../../../../pages/api/bookings/[id]/_auth-middleware";
1713
import handler from "../../../../../../pages/api/bookings/[id]/transcripts/[recordingId]/_get";
1814

@@ -31,7 +27,6 @@ vi.mock("~/lib/utils/retrieveScopedAccessibleUsers", () => {
3127
getAccessibleUsers: vi.fn(),
3228
};
3329
});
34-
3530
afterEach(() => {
3631
vi.resetAllMocks();
3732
});

apps/api/v1/test/lib/bookings/[id]/transcripts/_get.test.ts

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,11 @@
11
import prismaMock from "@calcom/testing/lib/__mocks__/prismaMock";
2-
2+
import { getAllTranscriptsAccessLinkFromRoomName } from "@calcom/features/conferencing/lib/videoClient";
3+
import { buildBooking } from "@calcom/lib/test/builder";
34
import type { Request, Response } from "express";
45
import type { NextApiRequest, NextApiResponse } from "next";
56
import { createMocks } from "node-mocks-http";
6-
import { describe, expect, test, vi, afterEach } from "vitest";
7-
8-
import { getAllTranscriptsAccessLinkFromRoomName } from "@calcom/features/conferencing/lib/videoClient";
9-
import { buildBooking } from "@calcom/lib/test/builder";
10-
7+
import { afterEach, describe, expect, test, vi } from "vitest";
118
import { getAccessibleUsers } from "~/lib/utils/retrieveScopedAccessibleUsers";
12-
139
import authMiddleware from "../../../../../pages/api/bookings/[id]/_auth-middleware";
1410
import handler from "../../../../../pages/api/bookings/[id]/transcripts/_get";
1511

@@ -27,7 +23,6 @@ vi.mock("~/lib/utils/retrieveScopedAccessibleUsers", () => {
2723
getAccessibleUsers: vi.fn(),
2824
};
2925
});
30-
3126
afterEach(() => {
3227
vi.resetAllMocks();
3328
});

apps/api/v1/test/lib/bookings/_post.test.ts

Lines changed: 58 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,62 @@
11
import prismaMock from "@calcom/testing/lib/__mocks__/prismaMock";
2-
3-
import type { Request, Response } from "express";
4-
import type { NextApiRequest, NextApiResponse } from "next";
5-
import { createMocks } from "node-mocks-http";
6-
import { describe, expect, test, vi, beforeEach } from "vitest";
7-
82
import dayjs from "@calcom/dayjs";
93
import { getEventTypesFromDB } from "@calcom/features/bookings/lib/handleNewBooking/getEventTypesFromDB";
104
import sendPayload from "@calcom/features/webhooks/lib/sendOrSchedulePayload";
115
import { ErrorCode } from "@calcom/lib/errorCodes";
12-
import { buildBooking, buildEventType, buildWebhook, buildUser } from "@calcom/lib/test/builder";
6+
import { buildBooking, buildEventType, buildUser, buildWebhook } from "@calcom/lib/test/builder";
137
import { prisma } from "@calcom/prisma";
148
import type { Booking } from "@calcom/prisma/client";
15-
import { CreationSource, BookingStatus } from "@calcom/prisma/enums";
16-
9+
import { BookingStatus, CreationSource } from "@calcom/prisma/enums";
10+
import type { Request, Response } from "express";
11+
import type { NextApiRequest, NextApiResponse } from "next";
12+
import { createMocks } from "node-mocks-http";
13+
import { beforeEach, describe, expect, test, vi } from "vitest";
1714
import handler from "../../../pages/api/bookings/_post";
1815

1916
vi.mock("@calcom/features/bookings/lib/handleNewBooking/getEventTypesFromDB", () => ({
2017
getEventTypesFromDB: vi.fn(),
2118
}));
2219

20+
vi.mock("@calcom/app-store/delegationCredential", () => ({
21+
enrichHostsWithDelegationCredentials: vi.fn().mockImplementation(({ hosts }) => hosts),
22+
enrichUsersWithDelegationCredentials: vi.fn().mockImplementation(({ users }) => users),
23+
enrichUserWithDelegationCredentialsIncludeServiceAccountKey: vi.fn().mockImplementation(({ user }) => user),
24+
enrichUserWithDelegationCredentials: vi.fn().mockImplementation(({ user }) => user),
25+
enrichUserWithDelegationConferencingCredentialsWithoutOrgId: vi.fn().mockImplementation(({ user }) => user),
26+
getUsersCredentialsIncludeServiceAccountKey: vi.fn().mockResolvedValue([]),
27+
getUsersCredentials: vi.fn().mockResolvedValue([]),
28+
getCredentialForSelectedCalendar: vi.fn(),
29+
getAllDelegationCredentialsForUserIncludeServiceAccountKey: vi.fn().mockResolvedValue([]),
30+
getAllDelegationCredentialsForUser: vi.fn().mockResolvedValue([]),
31+
getAllDelegatedCalendarCredentialsForUser: vi.fn().mockResolvedValue([]),
32+
getAllDelegationCredentialsForUserByAppType: vi.fn().mockResolvedValue([]),
33+
getAllDelegationCredentialsForUserByAppSlug: vi.fn().mockResolvedValue([]),
34+
buildAllCredentials: vi.fn().mockImplementation(({ existingCredentials }) => existingCredentials || []),
35+
getDelegationCredentialOrFindRegularCredential: vi.fn(),
36+
getDelegationCredentialOrRegularCredential: vi.fn(),
37+
getFirstDelegationConferencingCredential: vi.fn(),
38+
getFirstDelegationConferencingCredentialAppLocation: vi.fn(),
39+
findUniqueDelegationCalendarCredential: vi.fn(),
40+
assertSuccessfullyConfiguredInWorkspace: vi.fn(),
41+
}));
42+
43+
vi.mock("@calcom/features/calendars/lib/CalendarManager", () => ({
44+
createEvent: vi.fn(),
45+
updateEvent: vi.fn(),
46+
deleteEvent: vi.fn(),
47+
getBusyCalendarTimes: vi.fn(),
48+
}));
49+
50+
vi.mock("@calcom/features/auth/lib/verifyEmail", () => ({
51+
checkIfEmailIsBlockedInWatchlist: vi.fn(),
52+
isEmailVerified: vi.fn(),
53+
}));
54+
55+
vi.mock("@calcom/lib/domainManager/organization", () => ({
56+
getOrgDomainConfigFromHostname: vi.fn(),
57+
subdomainSuffix: vi.fn(),
58+
}));
59+
2360
const mockEventTypeData = {
2461
eventType: {
2562
id: 1,
@@ -66,9 +103,11 @@ vi.mock("@calcom/features/webhooks/lib/sendOrSchedulePayload", () => ({
66103

67104
const mockFindOriginalRescheduledBooking = vi.fn();
68105
vi.mock("@calcom/features/bookings/repositories/BookingRepository", () => ({
69-
BookingRepository: vi.fn().mockImplementation(function() { return {
70-
findOriginalRescheduledBooking: mockFindOriginalRescheduledBooking,
71-
}; }),
106+
BookingRepository: vi.fn().mockImplementation(function () {
107+
return {
108+
findOriginalRescheduledBooking: mockFindOriginalRescheduledBooking,
109+
};
110+
}),
72111
}));
73112

74113
vi.mock("@calcom/features/watchlist/operations/check-if-users-are-blocked.controller", () => ({
@@ -93,7 +132,7 @@ vi.mock("@calcom/features/di/containers/QualifiedHosts", () => ({
93132
}));
94133

95134
vi.mock("@calcom/features/bookings/lib/EventManager", () => ({
96-
default: vi.fn().mockImplementation(function() {
135+
default: vi.fn().mockImplementation(function () {
97136
return {
98137
reschedule: vi.fn().mockResolvedValue({
99138
results: [],
@@ -154,10 +193,12 @@ vi.mock("@calcom/features/profile/repositories/ProfileRepository", () => ({
154193
},
155194
}));
156195
vi.mock("@calcom/features/flags/features.repository", () => ({
157-
FeaturesRepository: vi.fn().mockImplementation(function() { return {
158-
checkIfFeatureIsEnabledGlobally: vi.fn().mockResolvedValue(false),
159-
checkIfTeamHasFeature: vi.fn().mockResolvedValue(false),
160-
}; }),
196+
FeaturesRepository: vi.fn().mockImplementation(function () {
197+
return {
198+
checkIfFeatureIsEnabledGlobally: vi.fn().mockResolvedValue(false),
199+
checkIfTeamHasFeature: vi.fn().mockResolvedValue(false),
200+
};
201+
}),
161202
}));
162203

163204
vi.mock("@calcom/features/webhooks/lib/getWebhooks", () => ({

apps/api/v1/test/lib/utils/isLockedOrBlocked.test.ts

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,23 @@
1-
import type { NextApiRequest } from "next";
2-
import { describe, expect, it, beforeEach, vi, afterEach } from "vitest";
3-
41
import { getWatchlistFeature } from "@calcom/features/di/watchlist/containers/watchlist";
52
import type { WatchlistFeature } from "@calcom/features/watchlist/lib/facade/WatchlistFeature";
6-
3+
import type { NextApiRequest } from "next";
4+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
75
import { isLockedOrBlocked } from "../../../lib/utils/isLockedOrBlocked";
86

97
vi.mock("@calcom/features/di/watchlist/containers/watchlist", () => ({
108
getWatchlistFeature: vi.fn(),
119
}));
1210

11+
vi.mock("@calcom/features/auth/lib/verifyEmail", () => ({
12+
sendEmailVerification: vi.fn(),
13+
verifyEmail: vi.fn(),
14+
}));
15+
16+
vi.mock("@calcom/prisma", () => ({
17+
default: {},
18+
prisma: {},
19+
}));
20+
1321
describe("isLockedOrBlocked", () => {
1422
let mockWatchlistFeature: WatchlistFeature;
1523

apps/web/app/(use-page-wrapper)/settings/(settings-layout)/organizations/actions/validateUserHasOrg.test.ts

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
1-
import type { Session } from "next-auth";
2-
import { redirect } from "next/navigation";
3-
import { describe, it, vi, expect, beforeEach, type MockedFunction } from "vitest";
4-
51
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
62
import { MembershipRole } from "@calcom/prisma/enums";
7-
8-
import { validateUserHasOrg, type ValidatedOrgSession } from "./validateUserHasOrg";
3+
import { redirect } from "next/navigation";
4+
import type { Session } from "next-auth";
5+
import { beforeEach, describe, expect, it, type MockedFunction, vi } from "vitest";
6+
import { type ValidatedOrgSession, validateUserHasOrg } from "./validateUserHasOrg";
97

108
// Mock the dependencies
119
vi.mock("next/navigation", () => ({
@@ -25,6 +23,11 @@ vi.mock("@lib/buildLegacyCtx", () => ({
2523
buildLegacyRequest: vi.fn(() => ({})),
2624
}));
2725

26+
vi.mock("@calcom/prisma", () => ({
27+
default: {},
28+
prisma: {},
29+
}));
30+
2831
const mockedGetServerSession = getServerSession as MockedFunction<typeof getServerSession>;
2932
const mockedRedirect = vi.mocked(redirect);
3033

apps/web/app/(use-page-wrapper)/settings/(settings-layout)/organizations/actions/validateUserHasOrgAdmin.test.ts

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
1-
import type { Session } from "next-auth";
2-
import { redirect } from "next/navigation";
3-
import { describe, it, vi, expect, beforeEach, type MockedFunction } from "vitest";
4-
51
import { checkAdminOrOwner } from "@calcom/features/auth/lib/checkAdminOrOwner";
62
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
73
import { MembershipRole } from "@calcom/prisma/enums";
8-
9-
import { validateUserHasOrgAdmin, type ValidatedOrgAdminSession } from "./validateUserHasOrgAdmin";
4+
import { redirect } from "next/navigation";
5+
import type { Session } from "next-auth";
6+
import { beforeEach, describe, expect, it, type MockedFunction, vi } from "vitest";
7+
import { type ValidatedOrgAdminSession, validateUserHasOrgAdmin } from "./validateUserHasOrgAdmin";
108

119
// Mock the dependencies
1210
vi.mock("next/navigation", () => ({
@@ -30,6 +28,11 @@ vi.mock("@lib/buildLegacyCtx", () => ({
3028
buildLegacyRequest: vi.fn(() => ({})),
3129
}));
3230

31+
vi.mock("@calcom/prisma", () => ({
32+
default: {},
33+
prisma: {},
34+
}));
35+
3336
const mockedGetServerSession = getServerSession as MockedFunction<typeof getServerSession>;
3437
const mockedCheckAdminOrOwner = vi.mocked(checkAdminOrOwner);
3538
const mockedRedirect = vi.mocked(redirect);

apps/web/app/api/routing-forms/queued-response/__tests__/queued-response.test.ts

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
11
import "@calcom/testing/lib/__mocks__/prisma";
2-
import { beforeEach, describe, it, expect, vi } from "vitest";
3-
42
import { onSubmissionOfFormResponse } from "@calcom/app-store/routing-forms/lib/formSubmissionUtils";
53
import { getResponseToStore } from "@calcom/app-store/routing-forms/lib/getResponseToStore";
64
import { getSerializableForm } from "@calcom/app-store/routing-forms/lib/getSerializableForm";
75
import { RoutingFormResponseRepository } from "@calcom/features/routing-forms/repositories/RoutingFormResponseRepository";
8-
6+
import { beforeEach, describe, expect, it, vi } from "vitest";
97
import { queuedResponseHandler } from "../route";
108

119
vi.mock("@calcom/features/routing-forms/repositories/RoutingFormResponseRepository");
@@ -17,7 +15,6 @@ const mockRoutingFormResponseRepository = {
1715
vi.mock("@calcom/app-store/routing-forms/lib/getSerializableForm");
1816
vi.mock("@calcom/app-store/routing-forms/lib/getResponseToStore");
1917
vi.mock("@calcom/app-store/routing-forms/lib/formSubmissionUtils");
20-
2118
const mockQueuedFormResponse = {
2219
id: "1",
2320
formId: "mock-form-id",
@@ -157,9 +154,9 @@ describe("queuedResponseHandler", () => {
157154

158155
vi.mocked(getResponseToStore).mockReturnValue({} as ReturnType<typeof getResponseToStore>);
159156

160-
vi.mocked(onSubmissionOfFormResponse).mockResolvedValue(undefined as unknown as Awaited<
161-
ReturnType<typeof onSubmissionOfFormResponse>
162-
>);
157+
vi.mocked(onSubmissionOfFormResponse).mockResolvedValue(
158+
undefined as unknown as Awaited<ReturnType<typeof onSubmissionOfFormResponse>>
159+
);
163160

164161
vi.mocked(mockRoutingFormResponseRepository.recordFormResponse).mockResolvedValue({
165162
id: 1,

apps/web/app/api/video/recording/__tests__/route.test.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
1-
import { NextResponse } from "next/server";
2-
import { describe, expect, test, vi, afterEach } from "vitest";
3-
41
import { getDownloadLinkOfCalVideoByRecordingId } from "@calcom/features/conferencing/lib/videoClient";
52
import { verifyVideoToken } from "@calcom/lib/videoTokens";
6-
3+
import { NextResponse } from "next/server";
4+
import { afterEach, describe, expect, test, vi } from "vitest";
75
import { GET } from "../route";
86

97
vi.mock("@calcom/features/conferencing/lib/videoClient", () => ({
@@ -14,6 +12,11 @@ vi.mock("@calcom/lib/videoTokens", () => ({
1412
verifyVideoToken: vi.fn(),
1513
}));
1614

15+
vi.mock("@calcom/prisma", () => ({
16+
default: {},
17+
prisma: {},
18+
}));
19+
1720
describe("GET /api/video/recording", () => {
1821
afterEach(() => {
1922
vi.resetAllMocks();

0 commit comments

Comments
 (0)