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
2 changes: 2 additions & 0 deletions docs/angular/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,8 @@ If you want to add a version-specific change, add the change inside of the appro

If you need to add E2E tests that are only run on a specific version of the JS Framework, replicate the `VersionTest` component on each partial application. This ensures that tests for framework version X do not get run for framework version Y.

For pages that only compile on some versions, `base/` ships an empty `version-test.routes.ts` under both `src/app/lazy/version-test/` and `src/app/standalone/version-test/`, mounted at `/lazy/version-test` and `/standalone/version-test`. Override that file in the apps that need the page, and put the page and its spec in those apps. Each app is built from `base/` plus only its own directory, so a variant app such as `ng22-zone` does not inherit from `ng22`. Add the files to both.

### Testing Lazy Loaded Ionic Components

Tests for lazy loaded Ionic UI components should only be added under the `/lazy` route. This ensures the `IonicModule` is added.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
import { AfterViewInit, ElementRef, Injector, OnDestroy, Directive, HostListener } from '@angular/core';
import {
AfterViewInit,
ElementRef,
EffectRef,
Injector,
OnDestroy,
Directive,
HostListener,
effect,
} from '@angular/core';
import { ControlValueAccessor, NgControl } from '@angular/forms';
import { Subscription } from 'rxjs';

Expand All @@ -15,13 +24,19 @@ export class ValueAccessor implements ControlValueAccessor, AfterViewInit, OnDes
/**/
};
protected lastValue: any;
/**
* The signal forms control bound to this element, if any. Pass it to
* `setIonicClasses` so the classes come from its state.
*/
protected signalControl?: NgControl;
private statusChanges?: Subscription;
private signalControlEffect?: EffectRef;

constructor(protected injector: Injector, protected elementRef: ElementRef) {}

writeValue(value: any): void {
this.elementRef.nativeElement.value = this.lastValue = value;
setIonicClasses(this.elementRef);
setIonicClasses(this.elementRef, this.signalControl);
}

/**
Expand All @@ -43,15 +58,15 @@ export class ValueAccessor implements ControlValueAccessor, AfterViewInit, OnDes
this.lastValue = value;
this.onChange(value);
}
setIonicClasses(this.elementRef);
setIonicClasses(this.elementRef, this.signalControl);
}
}

@HostListener('ionBlur', ['$event.target'])
_handleBlurEvent(el: any): void {
if (el === this.elementRef.nativeElement) {
this.onTouched();
setIonicClasses(this.elementRef);
setIonicClasses(this.elementRef, this.signalControl);

// When ion-radio is blurred, el and this.elementRef.nativeElement are
// different so we need to check if the closest ion-radio-group is the same
Expand All @@ -78,6 +93,7 @@ export class ValueAccessor implements ControlValueAccessor, AfterViewInit, OnDes
if (this.statusChanges) {
this.statusChanges.unsubscribe();
}
this.signalControlEffect?.destroy();
}

ngAfterViewInit(): void {
Expand All @@ -92,11 +108,21 @@ export class ValueAccessor implements ControlValueAccessor, AfterViewInit, OnDes
return;
}

// Listen for changes in validity, disabled, or pending states
if (ngControl.statusChanges) {
this.statusChanges = ngControl.statusChanges.subscribe(() => setIonicClasses(this.elementRef));
/**
* Signal forms (`[formField]`) provide an NgControl without
* `statusChanges` or `markAs*` methods, so there is nothing to
* subscribe to or patch. Its state getters read signals instead,
* so an effect re-runs whenever that state changes.
*/
if (!ngControl.statusChanges) {
const control = (this.signalControl = ngControl);
this.signalControlEffect = effect(() => setIonicClasses(this.elementRef, control), { injector: this.injector });
return;
}

// Listen for changes in validity, disabled, or pending states
this.statusChanges = ngControl.statusChanges.subscribe(() => setIonicClasses(this.elementRef));

/**
* TODO FW-2787: Remove this in favor of https://github.com/angular/angular/issues/10887
* whenever it is implemented.
Expand All @@ -117,11 +143,24 @@ export class ValueAccessor implements ControlValueAccessor, AfterViewInit, OnDes
}
}

export const setIonicClasses = (element: ElementRef): void => {
/**
* Sets the Ionic form status classes (`ion-touched`, `ion-invalid`, etc.)
* on the element and its parent item.
*
* @param element The component element.
* @param control A signal forms control. When passed, the classes are built
* from its state instead of copied from the `ng-*` classes on the element.
*/
export const setIonicClasses = (element: ElementRef, control?: NgControl): void => {
/**
* Read the control state before the raf so an effect calling this
* tracks the signals behind these getters.
*/
const stateClasses = control ? getStateClasses(control) : undefined;
raf(() => {
const input = element.nativeElement as HTMLInputElement;
const hasValue = input.value != null && input.value.toString().length > 0;
const classes = getClasses(input);
const classes = stateClasses ?? getClasses(input);
setClasses(input, classes);
const item = input.closest('ion-item');
if (item) {
Expand All @@ -134,6 +173,17 @@ export const setIonicClasses = (element: ElementRef): void => {
});
};

const getStateClasses = (control: NgControl): string[] => {
const classes = [control.touched ? 'ion-touched' : 'ion-untouched', control.dirty ? 'ion-dirty' : 'ion-pristine'];
// A pending control is neither valid nor invalid.
if (control.valid) {
classes.push('ion-valid');
} else if (control.invalid) {
classes.push('ion-invalid');
}
return classes;
};

const getClasses = (element: HTMLElement) => {
const classList = element.classList;
const classes: string[] = [];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export class BooleanValueAccessorDirective extends ValueAccessor {

writeValue(value: boolean): void {
this.elementRef.nativeElement.checked = this.lastValue = value;
setIonicClasses(this.elementRef);
setIonicClasses(this.elementRef, this.signalControl);
}

// Bind `$event` and cast `.target` in the body rather than `['$event.target']`:
Expand Down
2 changes: 1 addition & 1 deletion packages/angular/src/standalone/directives/checkbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ export class IonCheckbox extends ValueAccessor {

writeValue(value: boolean): void {
this.elementRef.nativeElement.checked = this.lastValue = value;
setIonicClasses(this.elementRef);
setIonicClasses(this.elementRef, this.signalControl);
}

@HostListener('ionChange', ['$event.target'])
Expand Down
2 changes: 1 addition & 1 deletion packages/angular/src/standalone/directives/toggle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ export class IonToggle extends ValueAccessor {

writeValue(value: boolean): void {
this.elementRef.nativeElement.checked = this.lastValue = value;
setIonicClasses(this.elementRef);
setIonicClasses(this.elementRef, this.signalControl);
}

@HostListener('ionChange', ['$event.target'])
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { test, expect } from '@playwright/test';

test.describe('Signal Forms: lazy', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/lazy/version-test/signal-forms');
});

test('should show the error text after the form is marked as touched', async ({ page }) => {
const name = page.locator('ion-input#name');

await page.locator('ion-button#submit').click();

await expect(name).toHaveClass(/\bion-touched\b/);
await expect(name).toHaveClass(/\bion-invalid\b/);
await expect(name.locator('.error-text')).toBeVisible();
});

test('should keep the status classes when the model checks a checkbox or toggle', async ({ page }) => {
const terms = page.locator('ion-checkbox#terms');
const notifications = page.locator('ion-toggle#notifications');

await page.locator('ion-button#submit').click();
await expect(terms).toHaveClass(/\bion-touched\b/);
await expect(notifications).toHaveClass(/\bion-touched\b/);

await page.locator('ion-button#check-all').click();

await expect(terms).toHaveJSProperty('checked', true);
await expect(notifications).toHaveJSProperty('checked', true);
await expect(terms).toHaveClass(/\bion-touched\b/);
await expect(notifications).toHaveClass(/\bion-touched\b/);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { test, expect } from '@playwright/test';

/**
* Ionic builds its status classes from the control state, so they must be
* the same whether or not the app opts into Angular's `ng-*` classes.
*/
const pages = [
{ title: 'without NG_STATUS_CLASSES', path: '/standalone/version-test/signal-forms' },
{ title: 'with NG_STATUS_CLASSES', path: '/standalone/version-test/signal-forms-status-classes' },
];

for (const { title, path } of pages) {
test.describe(`Signal Forms: ${title}`, () => {
test.beforeEach(async ({ page }) => {
await page.goto(path);
});

test('should show the error text after the form is marked as touched', async ({ page }) => {
const name = page.locator('ion-input#name');

await page.locator('ion-button#submit').click();

await expect(name).toHaveClass(/\bion-touched\b/);
await expect(name).toHaveClass(/\bion-invalid\b/);
await expect(name.locator('.error-text')).toBeVisible();
});

test('should update validity when it changes from another field', async ({ page }) => {
const confirm = page.locator('ion-input#confirm');

await expect(confirm).toHaveClass(/\bion-valid\b/);

await page.locator('ion-input#password input').fill('a');

await expect(confirm).toHaveClass(/\bion-invalid\b/);

await page.locator('ion-input#confirm input').fill('a');

await expect(confirm).toHaveClass(/\bion-valid\b/);
});

test('should keep the status classes after more typing and another blur', async ({ page }) => {
const name = page.locator('ion-input#name');
const nativeInput = name.locator('input');

await nativeInput.pressSequentially('ab');
await nativeInput.blur();
await nativeInput.focus();
await nativeInput.blur();

await expect(name).toHaveClass(/\bion-touched\b/);
await expect(name).toHaveClass(/\bion-dirty\b/);
await expect(name).toHaveClass(/\bion-valid\b/);
});

test('should keep the status classes when the model checks a checkbox or toggle', async ({ page }) => {
const terms = page.locator('ion-checkbox#terms');
const notifications = page.locator('ion-toggle#notifications');

await page.locator('ion-button#submit').click();
await expect(terms).toHaveClass(/\bion-touched\b/);
await expect(notifications).toHaveClass(/\bion-touched\b/);

await page.locator('ion-button#check-all').click();

await expect(terms).toHaveJSProperty('checked', true);
await expect(notifications).toHaveJSProperty('checked', true);
await expect(terms).toHaveClass(/\bion-touched\b/);
await expect(notifications).toHaveClass(/\bion-touched\b/);
});

test('should not mark a field as valid or invalid while async validation is pending', async ({ page }) => {
const username = page.locator('ion-input#username');

await expect(username).toHaveClass(/\bion-untouched\b/);
await expect(username).not.toHaveClass(/\bion-valid\b/);
await expect(username).not.toHaveClass(/\bion-invalid\b/);
});
});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { Component, signal } from '@angular/core';
import { FormField, form, required } from '@angular/forms/signals';
import { IonicModule } from '@ionic/angular/lazy';

@Component({
selector: 'app-signal-forms',
standalone: true,
imports: [FormField, IonicModule],
template: `
<ion-header>
<ion-toolbar>
<ion-title>Signal Forms</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-input id="name" label="Name" errorText="Name is required" [formField]="signupForm.name"></ion-input>
<ion-checkbox id="terms" [formField]="signupForm.terms">Accept terms</ion-checkbox>
<ion-toggle id="notifications" [formField]="signupForm.notifications">Notifications</ion-toggle>
<ion-button id="submit" (click)="signupForm().markAsTouched()">Submit</ion-button>
<ion-button id="check-all" (click)="checkAll()">Check all</ion-button>
</ion-content>
`,
})
export class SignalFormsComponent {
model = signal({ name: '', terms: false, notifications: false });

signupForm = form(this.model, (path) => {
required(path.name);
});

checkAll() {
this.model.update((model) => ({ ...model, terms: true, notifications: true }));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { Routes } from '@angular/router';

export const routes: Routes = [
{
path: 'signal-forms',
loadComponent: () => import('./signal-forms/signal-forms.component').then(c => c.SignalFormsComponent)
},
];
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { Component, resource, signal } from '@angular/core';
import { FormField, form, required, validate, validateAsync } from '@angular/forms/signals';
import { IonButton, IonCheckbox, IonContent, IonHeader, IonInput, IonTitle, IonToggle, IonToolbar } from '@ionic/angular';

@Component({
selector: 'app-signal-forms',
standalone: true,
imports: [FormField, IonButton, IonCheckbox, IonContent, IonHeader, IonInput, IonTitle, IonToggle, IonToolbar],
template: `
<ion-header>
<ion-toolbar>
<ion-title>Signal Forms</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-input id="name" label="Name" errorText="Name is required" [formField]="signupForm.name"></ion-input>
<ion-input id="password" label="Password" type="password" [formField]="signupForm.password"></ion-input>
<ion-input
id="confirm"
label="Confirm"
type="password"
errorText="Passwords must match"
[formField]="signupForm.confirm"
></ion-input>
<ion-input id="username" label="Username" [formField]="signupForm.username"></ion-input>
<ion-checkbox id="terms" [formField]="signupForm.terms">Accept terms</ion-checkbox>
<ion-toggle id="notifications" [formField]="signupForm.notifications">Notifications</ion-toggle>
<ion-button id="submit" (click)="signupForm().markAsTouched()">Submit</ion-button>
<ion-button id="check-all" (click)="checkAll()">Check all</ion-button>
</ion-content>
`,
})
export class SignalFormsComponent {
model = signal({ name: '', password: '', confirm: '', username: '', terms: false, notifications: false });

signupForm = form(this.model, (path) => {
required(path.name);
validate(path.confirm, ({ value, valueOf }) =>
value() === valueOf(path.password) ? undefined : { kind: 'mismatch', message: 'Passwords must match' }
);
// Never settles, so the field stays pending.
validateAsync(path.username, {
params: ({ value }) => value(),
factory: (params) => resource({ params, loader: () => new Promise<boolean>(() => {}) }),
onSuccess: () => undefined,
onError: () => undefined,
});
});

checkAll() {
this.model.update((model) => ({ ...model, terms: true, notifications: true }));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Routes } from '@angular/router';
import { NG_STATUS_CLASSES } from '@angular/forms/signals/compat';
import { provideSignalFormsConfig } from '@angular/forms/signals';

export const routes: Routes = [
{
path: 'signal-forms',
loadComponent: () => import('./signal-forms/signal-forms.component').then(c => c.SignalFormsComponent)
},
{
path: 'signal-forms-status-classes',
providers: [provideSignalFormsConfig({ classes: NG_STATUS_CLASSES })],
loadComponent: () => import('./signal-forms/signal-forms.component').then(c => c.SignalFormsComponent)
},
];
Loading
Loading