Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ export async function getVitestBuildOptions(
}

entryPoints.set('init-testbed', 'angular:test-bed-init');
entryPoints.set('vitest-mock-patch', 'angular:vitest-mock-patch');

// The 'vitest' package is always external for testing purposes
const externalDependencies = ['vitest'];
Expand Down Expand Up @@ -153,10 +154,22 @@ export async function getVitestBuildOptions(
buildOptions.polyfills,
);

const mockPatchContents = `
import { vi } from 'vitest';
const error = new Error(
'The "vi.mock" and related methods are not supported with the Angular unit-test system. Please use Angular TestBed for mocking.');
vi.mock = () => { throw error; };
vi.doMock = () => { throw error; };
vi.importMock = () => { throw error; };
vi.unmock = () => { throw error; };
vi.doUnmock = () => { throw error; };
`;

return {
buildOptions,
virtualFiles: {
'angular:test-bed-init': testBedInitContents,
'angular:vitest-mock-patch': mockPatchContents,
},
testEntryPointMappings: entryPoints,
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ export class VitestExecutor implements TestExecutor {
private prepareSetupFiles(): string[] {
const { setupFiles } = this.options;
// Add setup file entries for TestBed initialization and project polyfills
const testSetupFiles = ['init-testbed.js', ...setupFiles];
const testSetupFiles = ['init-testbed.js', 'vitest-mock-patch.js', ...setupFiles];

// TODO: Provide additional result metadata to avoid needing to extract based on filename
if (this.buildResultFiles.has('polyfills.js')) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { execute } from '../../index';
import {
BASE_OPTIONS,
describeBuilder,
UNIT_TEST_BUILDER_INFO,
setupApplicationTarget,
} from '../setup';

describeBuilder(execute, UNIT_TEST_BUILDER_INFO, (harness) => {
describe('Behavior: "Vitest mocking unsupported"', () => {
beforeEach(() => {
setupApplicationTarget(harness);
});

it('should fail when vi.mock is used', async () => {
harness.useTarget('test', {
...BASE_OPTIONS,
});

harness.writeFile(
'src/app/mock-throw.spec.ts',
`
import { vi } from 'vitest';
vi.mock('./something', () => ({}));
`,
);

// Overwrite default to avoid noise
harness.writeFile(
'src/app/app.component.spec.ts',
`
import { describe, it, expect } from 'vitest';
describe('Ignored', () => { it('pass', () => expect(true).toBe(true)); });
`,
);

const { result, logs } = await harness.executeOnce();
expect(result?.success).toBeFalse();
});
});
});