Skip to content
Merged
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 @@ -190,14 +190,18 @@ async function runEsbuild(
context: BuilderContext,
projectSourceRoot: string,
): Promise<[Result & { kind: ResultKind.Full }, AsyncIterator<Result> | null]> {
const usesZoneJS = buildOptions.polyfills?.includes('zone.js');
const virtualTestBedInit = createVirtualModulePlugin({
namespace: 'angular:test-bed-init',
loadContent: async () => {
const contents: string[] = [
// Initialize the Angular testing environment
`import { NgModule${usesZoneJS ? ', provideZoneChangeDetection' : ''} } from '@angular/core';`,
`import { getTestBed } from '@angular/core/testing';`,
`import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';`,
`getTestBed().initTestEnvironment(BrowserTestingModule, platformBrowserTesting(), {`,
`@NgModule({ providers: [${usesZoneJS ? 'provideZoneChangeDetection(), ' : ''}], })`,
`export class TestModule {}`,
`getTestBed().initTestEnvironment([BrowserTestingModule, TestModule], platformBrowserTesting(), {`,
` errorOnUnknownElements: true,`,
` errorOnUnknownProperties: true,`,
`});`,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ import { RunnerOptions } from '../api';
function createTestBedInitVirtualFile(
providersFile: string | undefined,
projectSourceRoot: string,
polyfills: string[] = [],
): string {
const usesZoneJS = polyfills.includes('zone.js');
let providersImport = 'const providers = [];';
if (providersFile) {
const relativePath = path.relative(projectSourceRoot, providersFile);
Expand All @@ -28,15 +30,15 @@ function createTestBedInitVirtualFile(

return `
// Initialize the Angular testing environment
import { NgModule } from '@angular/core';
import { NgModule${usesZoneJS ? ', provideZoneChangeDetection' : ''} } from '@angular/core';
import { getTestBed, ɵgetCleanupHook as getCleanupHook } from '@angular/core/testing';
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
${providersImport}
// Same as https://github.com/angular/angular/blob/05a03d3f975771bb59c7eefd37c01fa127ee2229/packages/core/testing/srcs/test_hooks.ts#L21-L29
beforeEach(getCleanupHook(false));
afterEach(getCleanupHook(true));
@NgModule({
providers,
providers: [${usesZoneJS ? 'provideZoneChangeDetection(), ' : ''}...providers],
})
export class TestModule {}
getTestBed().initTestEnvironment([BrowserTestingModule, TestModule], platformBrowserTesting(), {
Expand Down Expand Up @@ -113,7 +115,11 @@ export async function getVitestBuildOptions(

buildOptions.polyfills = injectTestingPolyfills(buildOptions.polyfills);

const testBedInitContents = createTestBedInitVirtualFile(providersFile, projectSourceRoot);
const testBedInitContents = createTestBedInitVirtualFile(
providersFile,
projectSourceRoot,
buildOptions.polyfills,
);

return {
buildOptions,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,16 @@
// TODO(dgp1130): These imports likely don't resolve in stricter package environments like `pnpm`, since they are resolved relative to
// `@angular-devkit/build-angular` rather than the user's workspace. Should look into virtual modules to support those use cases.

import { provideZoneChangeDetection, NgModule } from '@angular/core';
import { getTestBed } from '@angular/core/testing';
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';

getTestBed().initTestEnvironment(BrowserTestingModule, platformBrowserTesting(), {
@NgModule({
providers: [typeof window.Zone !== 'undefined' ? provideZoneChangeDetection() : []],
})
class TestModule {}

getTestBed().initTestEnvironment([BrowserTestingModule, TestModule], platformBrowserTesting(), {
errorOnUnknownElements: true,
errorOnUnknownProperties: true,
});
Original file line number Diff line number Diff line change
Expand Up @@ -149,14 +149,18 @@ async function initializeBrowser(
return [karma, (await webpackConfigurationTransformer?.(config)) ?? config];
}

function getBuiltInMainFile(): string {
function getBuiltInMainFile(includeZoneProvider = false): string {
const content = Buffer.from(
`
import { provideZoneChangeDetection, ɵcompileNgModuleDefs as compileNgModuleDefs } from '@angular/core';
import { getTestBed } from '@angular/core/testing';
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';

export class TestModule {}
compileNgModuleDefs(TestModule, {providers: [${includeZoneProvider ? 'provideZoneChangeDetection()' : ''}]});

// Initialize the Angular testing environment.
getTestBed().initTestEnvironment(BrowserTestingModule, platformBrowserTesting(), {
getTestBed().initTestEnvironment([BrowserTestingModule, TestModule], platformBrowserTesting(), {
errorOnUnknownElements: true,
errorOnUnknownProperties: true
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
* found in the LICENSE file at https://angular.dev/license
*/

import { NgModule } from '@angular/core';
import { getTestBed } from '@angular/core/testing';
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
import {
Expand Down Expand Up @@ -63,8 +64,13 @@ export async function runJasmineTests(jasmineEnv) {
// eslint-disable-next-line no-undef
jasmine.DEFAULT_TIMEOUT_INTERVAL = config.defaultTimeoutInterval;

@NgModule({
providers: [typeof window.Zone !== 'undefined' ? provideZoneChangeDetection() : []],
})
class TestModule {}

// Initialize `TestBed` automatically for users. This assumes we already evaluated `zone.js/testing`.
getTestBed().initTestEnvironment(BrowserTestingModule, platformBrowserTesting(), {
getTestBed().initTestEnvironment([BrowserTestingModule, TestModule], platformBrowserTesting(), {
errorOnUnknownElements: true,
errorOnUnknownProperties: true,
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { NgModule, provideBrowserGlobalErrorListeners<% if(zoneless) { %>, provideZonelessChangeDetection<% } %> } from '@angular/core';
import { NgModule, provideBrowserGlobalErrorListeners } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
<% if (routing) { %>
import { AppRoutingModule } from './app-routing-module';<% } %>
Expand All @@ -13,8 +13,7 @@ import { App } from './app';
AppRoutingModule<% } %>
],
providers: [
provideBrowserGlobalErrorListeners()<% if (zoneless) { %>,
provideZonelessChangeDetection()<% } %>
provideBrowserGlobalErrorListeners()
],
bootstrap: [App]
})
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
<% if(zoneless) { %>import { provideZonelessChangeDetection } from '@angular/core';
<% } %>import { TestBed } from '@angular/core/testing';<% if (routing) { %>
import { TestBed } from '@angular/core/testing';<% if (routing) { %>
import { RouterModule } from '@angular/router';<% } %>
import { App } from './app';

Expand All @@ -11,8 +10,7 @@ describe('App', () => {
],<% } %>
declarations: [
App
],<% if(zoneless) { %>
providers: [provideZonelessChangeDetection()]<% } %>
],
}).compileComponents();
});

Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { ApplicationConfig, provideBrowserGlobalErrorListeners, <% if(!zoneless) { %>provideZoneChangeDetection<% } else { %>provideZonelessChangeDetection<% } %> } from '@angular/core';<% if (routing) { %>
import { ApplicationConfig, provideBrowserGlobalErrorListeners<% if(!zoneless) { %>, provideZoneChangeDetection<% } %> } from '@angular/core';<% if (routing) { %>
import { provideRouter } from '@angular/router';

import { routes } from './app.routes';<% } %>

export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
<% if(zoneless) { %>provideZonelessChangeDetection()<% } else { %>provideZoneChangeDetection({ eventCoalescing: true })<% } %>,
provideBrowserGlobalErrorListeners(),<% if(!zoneless) { %>
provideZoneChangeDetection({ eventCoalescing: true }),<% } %>
<% if (routing) {%>provideRouter(routes)<% } %>
]
};
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
<% if(zoneless) { %>import { provideZonelessChangeDetection } from '@angular/core';
<% } %>import { TestBed } from '@angular/core/testing';
import { TestBed } from '@angular/core/testing';
import { App } from './app';

describe('App', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [App],<% if(zoneless) { %>
providers: [provideZonelessChangeDetection()]<% } %>
imports: [App],
}).compileComponents();
});

Expand Down
64 changes: 11 additions & 53 deletions packages/schematics/angular/application/index_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ describe('Application Schematic', () => {
expect(pkg.devDependencies['less']).toEqual(latestVersions['less']);
});

it('should include zone.js if "zoneless" option is not present', async () => {
it('should _not_ include zone.js if "zoneless" option is not present', async () => {
const tree = await schematicRunner.runSchematic(
'application',
{
Expand All @@ -307,7 +307,7 @@ describe('Application Schematic', () => {
);

const pkg = JSON.parse(tree.readContent('/package.json'));
expect(pkg.dependencies['zone.js']).toEqual(latestVersions['zone.js']);
expect(pkg.dependencies['zone.js']).toBeUndefined();
});

it('should not include zone.js if "zoneless" option is true', async () => {
Expand Down Expand Up @@ -389,7 +389,7 @@ describe('Application Schematic', () => {
expect(buildOpt.index).toBeUndefined();
expect(buildOpt.browser).toEqual('src/main.ts');
expect(buildOpt.assets).toEqual([{ 'glob': '**/*', 'input': 'public' }]);
expect(buildOpt.polyfills).toEqual(['zone.js']);
expect(buildOpt.polyfills).toEqual(undefined);
expect(buildOpt.tsConfig).toEqual('tsconfig.app.json');

const testOpt = prj.architect.test.options;
Expand Down Expand Up @@ -478,7 +478,7 @@ describe('Application Schematic', () => {
expect(project.root).toEqual('foo');
const buildOpt = project.architect.build.options;
expect(buildOpt.browser).toEqual('foo/src/main.ts');
expect(buildOpt.polyfills).toEqual(['zone.js']);
expect(buildOpt.polyfills).toEqual(undefined);
expect(buildOpt.tsConfig).toEqual('foo/tsconfig.app.json');
expect(buildOpt.assets).toEqual([{ 'glob': '**/*', 'input': 'foo/public' }]);

Expand Down Expand Up @@ -650,8 +650,8 @@ describe('Application Schematic', () => {
expect(moduleFiles.length).toEqual(0);
});

it('should enable zone event coalescing by default', async () => {
const options = { ...defaultOptions, standalone: true };
it('should enable zone event coalescing by default for zone.js apps', async () => {
const options = { ...defaultOptions, standalone: true, zoneless: false };

const tree = await schematicRunner.runSchematic('application', options, workspaceTree);
const appConfig = tree.readContent('/projects/foo/src/app/app.config.ts');
Expand Down Expand Up @@ -692,12 +692,13 @@ describe('Application Schematic', () => {
});

describe('standalone=false', () => {
it('should add the ngZoneEventCoalescing option by default', async () => {
it('should add the ngZoneEventCoalescing option by default with zone.js apps', async () => {
const tree = await schematicRunner.runSchematic(
'application',
{
...defaultOptions,
standalone: false,
zoneless: false,
},
workspaceTree,
);
Expand Down Expand Up @@ -800,7 +801,7 @@ describe('Application Schematic', () => {
);
});

it('should add provideZonelessChangeDetection() in app-module.ts when zoneless is true', async () => {
it('should not add provideZonelessChangeDetection() in app-module.ts when zoneless is true', async () => {
const tree = await schematicRunner.runSchematic(
'application',
{
Expand All @@ -812,53 +813,10 @@ describe('Application Schematic', () => {
);
const path = '/projects/foo/src/app/app-module.ts';
const fileContent = tree.readContent(path);
expect(fileContent).toContain('provideZonelessChangeDetection()');
});

it('should not add provideZonelessChangeDetection() in app-module.ts when zoneless is false', async () => {
const tree = await schematicRunner.runSchematic(
'application',
{
...defaultOptions,
zoneless: false,
standalone: false,
},
workspaceTree,
);
const path = '/projects/foo/src/app/app-module.ts';
const fileContent = tree.readContent(path);
expect(fileContent).not.toContain('provideZonelessChangeDetection()');
});

it('should add provideZonelessChangeDetection() when zoneless is true', async () => {
const tree = await schematicRunner.runSchematic(
'application',
{
...defaultOptions,
zoneless: true,
},
workspaceTree,
);
const path = '/projects/foo/src/app/app.config.ts';
const fileContent = tree.readContent(path);
expect(fileContent).toContain('provideZonelessChangeDetection()');
});

it('should not add provideZonelessChangeDetection() when zoneless is false', async () => {
const tree = await schematicRunner.runSchematic(
'application',
{
...defaultOptions,
zoneless: false,
},
workspaceTree,
);
const path = '/projects/foo/src/app/app.config.ts';
const fileContent = tree.readContent(path);
expect(fileContent).not.toContain('provideZonelessChangeDetection()');
});

it('should not add provideZoneChangeDetection when zoneless is true', async () => {
it('should not add any change detection provider when zoneless is true', async () => {
const tree = await schematicRunner.runSchematic(
'application',
{
Expand All @@ -869,7 +827,7 @@ describe('Application Schematic', () => {
);
const path = '/projects/foo/src/app/app.config.ts';
const fileContent = tree.readContent(path);
expect(fileContent).not.toContain('provideZoneChangeDetection');
expect(fileContent).not.toMatch(/provideZone(less)?ChangeDetection/gi);
});
});

Expand Down
2 changes: 1 addition & 1 deletion packages/schematics/angular/application/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@
"description": "Generate an application that does not use `zone.js`.",
"x-prompt": "Do you want to create a 'zoneless' application without zone.js?",
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are we keeping the prompt?

"type": "boolean",
"default": false
"default": true
},
"fileNameStyleGuide": {
"type": "string",
Expand Down
2 changes: 1 addition & 1 deletion packages/schematics/angular/service-worker/index_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ describe('Service Worker Schematic', () => {
const tree = await schematicRunner.runSchematic('service-worker', defaultOptions, appTree);
const content = tree.readContent('/projects/bar/src/app/app.config.ts');
expect(content).toContain(
`import { ApplicationConfig, provideBrowserGlobalErrorListeners, provideZoneChangeDetection, isDevMode } from '@angular/core';`,
`import { ApplicationConfig, provideBrowserGlobalErrorListeners, isDevMode } from '@angular/core';`,
);
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -447,7 +447,6 @@ describe('standalone utilities', () => {
content,
`providers: [
provideBrowserGlobalErrorListeners(),
provideZoneChangeDetection({ eventCoalescing:true }),
provideModule([]),
]`,
);
Expand Down
3 changes: 1 addition & 2 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion tests/legacy-cli/e2e/initialize/500-create-project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export default async function () {
// Ensure local test registry is used when outside a project
await setNPMConfigRegistry(true);

await ng('new', 'test-project', '--skip-install');
await ng('new', 'test-project', '--skip-install', '--no-zoneless');
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In a followup we should likely try to have most of the our tests test the default behavior (IE: zoneless).

await expectFileToExist(join(process.cwd(), 'test-project'));
process.chdir('./test-project');

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,15 @@ import { updateJsonFile } from '../../../utils/project';
const snapshots = require('../../../ng-snapshot/package.json');

export default async function () {
await ng('generate', 'app', 'test-project-two', '--routing', '--no-standalone', '--skip-install');
await ng(
'generate',
'app',
'test-project-two',
'--routing',
'--no-standalone',
'--skip-install',
'--no-zoneless',
);
await ng('generate', 'app-shell', '--project', 'test-project-two');

const isSnapshotBuild = getGlobalVariable('argv')['ng-snapshots'];
Expand Down
Loading