Skip to content

Commit e558117

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.
1 parent f1ed025 commit e558117

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
@@ -187,31 +187,36 @@ export async function getVitestBuildOptions(
187187
const mockPatchContents = `
188188
import { vi } from 'vitest';
189189
190-
const error = new Error(
191-
'The "vi.mock" and related methods are not supported for relative imports with the Angular unit-test system. ' +
192-
'Please use Angular TestBed for mocking dependencies.'
193-
);
194-
195-
// Store original implementations
196-
const { mock, doMock, importMock, unmock, doUnmock } = vi;
197-
198-
function patch(original) {
199-
return (path, ...args) => {
200-
// Check if the path is a string and starts with a character that indicates a relative path.
201-
if (typeof path === 'string' && /^[./]/.test(path)) {
202-
throw error;
203-
}
204-
205-
// Call the original function for non-relative paths.
206-
return original(path, ...args);
207-
};
190+
const ANGULAR_VITEST_MOCK_PATCH = Symbol.for('@angular/cli/vitest-mock-patch');
191+
if (!globalThis[ANGULAR_VITEST_MOCK_PATCH]) {
192+
globalThis[ANGULAR_VITEST_MOCK_PATCH] = true;
193+
194+
const error = new Error(
195+
'The "vi.mock" and related methods are not supported for relative imports with the Angular unit-test system. ' +
196+
'Please use Angular TestBed for mocking dependencies.'
197+
);
198+
199+
// Store original implementations
200+
const { mock, doMock, importMock, unmock, doUnmock } = vi;
201+
202+
function patch(original) {
203+
return (path, ...args) => {
204+
// Check if the path is a string and starts with a character that indicates a relative path.
205+
if (typeof path === 'string' && /^[./]/.test(path)) {
206+
throw error;
207+
}
208+
209+
// Call the original function for non-relative paths.
210+
return original(path, ...args);
211+
};
212+
}
213+
214+
vi.mock = patch(mock);
215+
vi.doMock = patch(doMock);
216+
vi.importMock = patch(importMock);
217+
vi.unmock = patch(unmock);
218+
vi.doUnmock = patch(doUnmock);
208219
}
209-
210-
vi.mock = patch(mock);
211-
vi.doMock = patch(doMock);
212-
vi.importMock = patch(importMock);
213-
vi.unmock = patch(unmock);
214-
vi.doUnmock = patch(doUnmock);
215220
`;
216221

217222
return {

0 commit comments

Comments
 (0)