Skip to content

test(compiler): add unit tests for buildAndAnalyzeWithParallelCompilation #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
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
@@ -0,0 +1,106 @@
import { beforeEach, describe, expect, it } from 'vitest';
import { buildAndAnalyzeWithParallelCompilation } from './build-and-analyze'; // Adjust path accordingly
import { ParallelCompilation } from '@angular/build/src/tools/angular/compilation/parallel-compilation';
import { JavaScriptTransformer } from '@angular/build/src/tools/esbuild/javascript-transformer';
import * as path from 'node:path';

describe('buildAndAnalyzeWithParallelCompilation execution', () => {
let parallelCompilation: ParallelCompilation;
let javascriptTransformer: JavaScriptTransformer;
let typescriptFileCache: Map<string, string | Uint8Array>;

beforeEach(async () => {
typescriptFileCache = new Map();

parallelCompilation = new ParallelCompilation(false, false);
const tsConfigPath =
'./mocks/fixtures/integration/tsconfig-variations/tsconfig.minimal.json';

await parallelCompilation.initialize(tsConfigPath, {
transformStylesheet(_: string, __: string): Promise<string | null> {
return Promise.resolve('MOCK_TRANSFORMED_STYLESHEET');
},
processWebWorker: (_: string, __: string) => 'PROCESS_WEB_WORKER',
});

javascriptTransformer = new JavaScriptTransformer(
{
jit: false,
sourcemap: false,
},
3
);
});

it('should compile and cache transformed TypeScript files', async () => {
const transformDataSpy = vi.spyOn(javascriptTransformer, 'transformData');
await expect(
buildAndAnalyzeWithParallelCompilation(
parallelCompilation,
typescriptFileCache,
javascriptTransformer
)
).resolves.not.toThrow();
expect(typescriptFileCache.size).toBe(2);
expect(transformDataSpy).toHaveBeenCalledTimes(2);

const constTransformedContent = typescriptFileCache.get(
path.join(
process.cwd(),
'mocks/fixtures/integration/tsconfig-variations/const-export.ts'
)
);
expect(constTransformedContent).toMatchInlineSnapshot(`
""use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.num42 = void 0;
exports.num42 = 42;
"
`);
const compTransformedContent = typescriptFileCache.get(
path.join(
process.cwd(),
'mocks/fixtures/integration/tsconfig-variations/component-export.ts'
)
);
expect(compTransformedContent).toMatchInlineSnapshot(`
""use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ComponentExport = void 0;
const core_1 = require("@angular/core");
const i0 = __importStar(require("@angular/core"));
class ComponentExport {
static ɵfac = function ComponentExport_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || ComponentExport)(); };
static ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent({ type: ComponentExport, selectors: [["ng-component"]], decls: 1, vars: 0, template: function ComponentExport_Template(rf, ctx) { if (rf & 1) {
i0.ɵɵtext(0, "Component Export");
} }, styles: ["MOCK_TRANSFORMED_STYLESHEET"] });
}
exports.ComponentExport = ComponentExport;
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassDebugInfo(ComponentExport, { className: "ComponentExport", filePath: "mocks/fixtures/integration/tsconfig-variations/component-export.ts", lineNumber: 13 }); })();
"
`);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { buildAndAnalyzeWithParallelCompilation } from './build-and-analyze';
import { ParallelCompilation } from '@angular/build/src/tools/angular/compilation/parallel-compilation';
import { JavaScriptTransformer } from '@angular/build/src/tools/esbuild/javascript-transformer';

describe('buildAndAnalyzeWithParallelCompilation', () => {
let parallelCompilation: ParallelCompilation;
let javascriptTransformer: JavaScriptTransformer;
let typescriptFileCache: Map<string, string | Uint8Array>;
const mockEmitAffectedFiles = vi.fn();
const mockTransformData = vi.fn();

beforeEach(() => {
vi.clearAllMocks();

mockTransformData.mockImplementation((_file, _) =>
Promise.resolve('MOCK_TRANSFORMED')
);

parallelCompilation = {
emitAffectedFiles: mockEmitAffectedFiles,
} as unknown as ParallelCompilation;
javascriptTransformer = {
transformData: mockTransformData,
} as unknown as JavaScriptTransformer;
typescriptFileCache = new Map<string, string | Uint8Array>();
});

it('should call emitAffectedFiles and iterate over result of emitted files', async () => {
mockEmitAffectedFiles.mockResolvedValue([
{ filename: 'file1.ts', contents: '' },
{ filename: 'file2.ts', contents: '' },
]);

await expect(
buildAndAnalyzeWithParallelCompilation(
parallelCompilation,
typescriptFileCache,
javascriptTransformer
)
).resolves.not.toThrow();
expect(mockEmitAffectedFiles).toHaveBeenCalledTimes(1);
expect(mockTransformData).toHaveBeenCalledTimes(2);
});

it('should normalize file names before emitting', async () => {
mockEmitAffectedFiles.mockResolvedValue([
{ filename: 'C:/file.ts', contents: '' },
]);

await expect(
buildAndAnalyzeWithParallelCompilation(
parallelCompilation,
typescriptFileCache,
javascriptTransformer
)
).resolves.not.toThrow();

expect(mockTransformData).toHaveBeenNthCalledWith(
1,
'/file.ts',
'',
true,
false
);
});

it('should add emitted files to cache', async () => {
mockEmitAffectedFiles.mockResolvedValue([
{ filename: 'file.ts', contents: '' },
]);
await expect(
buildAndAnalyzeWithParallelCompilation(
parallelCompilation,
typescriptFileCache,
javascriptTransformer
)
).resolves.not.toThrow();

expect(typescriptFileCache.size).toBe(1);
expect(typescriptFileCache.has('file.ts')).toBe(true);
expect(typescriptFileCache.get('file.ts')).toEqual(expect.any(String));
});

it('should transform the file content', async () => {
mockEmitAffectedFiles.mockResolvedValue([
{ filename: 'file.ts', contents: '' },
]);
await expect(
buildAndAnalyzeWithParallelCompilation(
parallelCompilation,
typescriptFileCache,
javascriptTransformer
)
).resolves.not.toThrow();

expect(mockTransformData).toHaveBeenCalledTimes(1);
expect(typescriptFileCache.get('file.ts')).toBe('MOCK_TRANSFORMED');
});
});
31 changes: 2 additions & 29 deletions packages/angular-rspack-compiler/src/models/index.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,9 @@
import { JavaScriptTransformer } from '@angular/build/src/tools/esbuild/javascript-transformer';
import { ParallelCompilation } from '@angular/build/src/tools/angular/compilation/parallel-compilation';

export { ParallelCompilation, JavaScriptTransformer };

export * from './inline-style-language';
export * from './file-replacement';
export * from './style-preprocessor-options';

export enum DiagnosticModes {
None = 0,
Option = 1 << 0,
Syntactic = 1 << 1,
Semantic = 1 << 2,
All = Option | Syntactic | Semantic,
}
export interface Location {
file: string;
namespace: string;
line: number;
column: number;
length: number;
lineText: string;
suggestion: string;
}
export interface PartialNote {
text?: string;
location?: Partial<Location> | null;
}
export interface PartialMessage {
id?: string;
pluginName?: string;
text?: string;
location?: Partial<Location> | null;
notes?: PartialNote[];
detail?: never;
}
export * from './nodes';
28 changes: 28 additions & 0 deletions packages/angular-rspack-compiler/src/models/nodes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
export enum DiagnosticModes {
None = 0,
Option = 1 << 0,
Syntactic = 1 << 1,
Semantic = 1 << 2,
All = Option | Syntactic | Semantic,
}
export interface Location {
file: string;
namespace: string;
line: number;
column: number;
length: number;
lineText: string;
suggestion: string;
}
export interface PartialNote {
text?: string;
location?: Partial<Location> | null;
}
export interface PartialMessage {
id?: string;
pluginName?: string;
text?: string;
location?: Partial<Location> | null;
notes?: PartialNote[];
detail?: never;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Component } from '@angular/core';

@Component({
template: 'Component Export',
styles: [
`
p {
color: #000;
}
`,
],
})
export class ComponentExport {}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const num42 = 42;
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"compilerOptions": {
"target": "es2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"files": [
"packages/compiler/mocks/fixtures/integration/tsconfig-variations/const-export.ts",
"packages/compiler/mocks/fixtures/integration/tsconfig-variations/component-export.ts"
]
}
}
1 change: 1 addition & 0 deletions testing/setup/src/index.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export const EXCLUDED_FILES_TEST = [
'mocks/**',
'**/types.ts',
'**/index.ts',
'**/*.d.ts',
'__snapshots__/**',
'**/__tests__/**',
Expand Down
Loading