Skip to content

Commit 8186faa

Browse files
committed
fix(@angular/build): ensure Vitest mock patching is executed only once
Wrap the Vitest mocking overrides in a global guard to prevent repeated execution in shared environments or watch mode runs. (cherry picked from commit e558117)
1 parent 7d3844a commit 8186faa

File tree

1 file changed

+29
-24
lines changed

1 file changed

+29
-24
lines changed

packages/angular/build/src/builders/unit-test/runners/vitest/build-options.ts

Lines changed: 29 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -157,31 +157,36 @@ export async function getVitestBuildOptions(
157157
const mockPatchContents = `
158158
import { vi } from 'vitest';
159159
160-
const error = new Error(
161-
'The "vi.mock" and related methods are not supported for relative imports with the Angular unit-test system. ' +
162-
'Please use Angular TestBed for mocking dependencies.'
163-
);
164-
165-
// Store original implementations
166-
const { mock, doMock, importMock, unmock, doUnmock } = vi;
167-
168-
function patch(original) {
169-
return (path, ...args) => {
170-
// Check if the path is a string and starts with a character that indicates a relative path.
171-
if (typeof path === 'string' && /^[./]/.test(path)) {
172-
throw error;
173-
}
174-
175-
// Call the original function for non-relative paths.
176-
return original(path, ...args);
177-
};
160+
const ANGULAR_VITEST_MOCK_PATCH = Symbol.for('@angular/cli/vitest-mock-patch');
161+
if (!globalThis[ANGULAR_VITEST_MOCK_PATCH]) {
162+
globalThis[ANGULAR_VITEST_MOCK_PATCH] = true;
163+
164+
const error = new Error(
165+
'The "vi.mock" and related methods are not supported for relative imports with the Angular unit-test system. ' +
166+
'Please use Angular TestBed for mocking dependencies.'
167+
);
168+
169+
// Store original implementations
170+
const { mock, doMock, importMock, unmock, doUnmock } = vi;
171+
172+
function patch(original) {
173+
return (path, ...args) => {
174+
// Check if the path is a string and starts with a character that indicates a relative path.
175+
if (typeof path === 'string' && /^[./]/.test(path)) {
176+
throw error;
177+
}
178+
179+
// Call the original function for non-relative paths.
180+
return original(path, ...args);
181+
};
182+
}
183+
184+
vi.mock = patch(mock);
185+
vi.doMock = patch(doMock);
186+
vi.importMock = patch(importMock);
187+
vi.unmock = patch(unmock);
188+
vi.doUnmock = patch(doUnmock);
178189
}
179-
180-
vi.mock = patch(mock);
181-
vi.doMock = patch(doMock);
182-
vi.importMock = patch(importMock);
183-
vi.unmock = patch(unmock);
184-
vi.doUnmock = patch(doUnmock);
185190
`;
186191

187192
return {

0 commit comments

Comments
 (0)