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
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` and needs its own copy of the files.

### 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,
DoCheck,
ElementRef,
Injector,
OnDestroy,
Directive,
HostListener,
effect,
} from '@angular/core';
import { ControlValueAccessor, NgControl } from '@angular/forms';
import { Subscription } from 'rxjs';

Expand All @@ -7,21 +16,29 @@ import { raf } from '../../utils/util';
// TODO(FW-2827): types

@Directive()
export class ValueAccessor implements ControlValueAccessor, AfterViewInit, OnDestroy {
export class ValueAccessor implements ControlValueAccessor, AfterViewInit, DoCheck, OnDestroy {
private onChange: (value: any) => void = () => {
/**/
};
private onTouched: () => void = () => {
/**/
};
protected lastValue: any;
private signalControl?: NgControl;
private statusChanges?: Subscription;
private reactiveControl?: NgControl;
private lastReactiveState?: string;

constructor(protected injector: Injector, protected elementRef: ElementRef) {}
Comment thread
thetaPC marked this conversation as resolved.
Resolved

/** Falls back to copying the `ng-*` classes until a control is set. */
protected updateIonicClasses(): void {
setIonicClasses(this.elementRef, this.signalControl ?? this.reactiveControl);
}

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

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

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

// 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 @@ -74,28 +91,49 @@ export class ValueAccessor implements ControlValueAccessor, AfterViewInit, OnDes
this.elementRef.nativeElement.disabled = isDisabled;
}

/**
* Angular validates with `emitEvent: false` during setup, so an async
* validator can settle without emitting `statusChanges`.
*/
ngDoCheck(): void {
if (!this.reactiveControl) {
return;
}
const state = getStateClasses(this.reactiveControl).join(' ');
if (state !== this.lastReactiveState) {
this.lastReactiveState = state;
this.updateIonicClasses();
}
}

ngOnDestroy(): void {
if (this.statusChanges) {
this.statusChanges.unsubscribe();
}
}

ngAfterViewInit(): void {
let ngControl;
try {
ngControl = this.injector.get<NgControl>(NgControl);
} catch {
/* No FormControl or ngModel binding */
// A control bound to an ancestor, like a wrapper component, can cover several inputs.
const ngControl = this.injector.get(NgControl, null, { self: true });
if (!ngControl) {
return;
}

if (!ngControl) {
/**
* Signal forms provide an NgControl with no `statusChanges` or `markAs*`
* methods, but its getters read signals, so an effect tracks them.
*/
if (!ngControl.statusChanges) {
this.signalControl = ngControl;
effect(() => this.updateIonicClasses(), { injector: this.injector });
return;
}

this.reactiveControl = ngControl;
this.lastReactiveState = getStateClasses(ngControl).join(' ');

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

/**
* TODO FW-2787: Remove this in favor of https://github.com/angular/angular/issues/10887
Expand All @@ -109,19 +147,25 @@ export class ValueAccessor implements ControlValueAccessor, AfterViewInit, OnDes
const oldFn = formControl[method].bind(formControl);
formControl[method] = (...params: any[]) => {
oldFn(...params);
setIonicClasses(this.elementRef);
this.updateIonicClasses();
};
}
});
}
}
}

export const setIonicClasses = (element: ElementRef): void => {
/**
* Sets the Ionic form status classes on the element and its parent item. When
* `control` is passed, they come from its state instead of the `ng-*` classes.
*/
export const setIonicClasses = (element: ElementRef, control?: NgControl): void => {
// Read the state outside the raf so a calling effect tracks its signals.
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 +178,18 @@ 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'];
if (control.valid) {
classes.push('ion-valid');
} else if (control.invalid) {
classes.push('ion-invalid');
} else if (control.pending) {
classes.push('ion-pending');
}
return classes;
};

const getClasses = (element: HTMLElement) => {
const classList = element.classList;
const classes: string[] = [];
Expand All @@ -148,7 +204,15 @@ const getClasses = (element: HTMLElement) => {

const setClasses = (element: HTMLElement, classes: string[]) => {
const classList = element.classList;
classList.remove('ion-valid', 'ion-invalid', 'ion-touched', 'ion-untouched', 'ion-dirty', 'ion-pristine');
classList.remove(
'ion-valid',
'ion-invalid',
'ion-pending',
'ion-touched',
'ion-untouched',
'ion-dirty',
'ion-pristine'
);
classList.add(...classes);
};

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Directive, HostListener, ElementRef, Injector } from '@angular/core';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
import { ValueAccessor, setIonicClasses } from '@ionic/angular/common';
import { ValueAccessor } from '@ionic/angular/common';

@Directive({
standalone: false,
Expand All @@ -20,7 +20,7 @@ export class BooleanValueAccessorDirective extends ValueAccessor {

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

// Bind `$event` and cast `.target` in the body rather than `['$event.target']`:
Expand Down
4 changes: 2 additions & 2 deletions packages/angular/src/standalone/directives/checkbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
forwardRef,
} from '@angular/core';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
import { ValueAccessor, setIonicClasses } from '@ionic/angular/common';
import { ValueAccessor } from '@ionic/angular/common';
import type { CheckboxChangeEventDetail, Components } from '@ionic/core/components';
import { defineCustomElement } from '@ionic/core/components/ion-checkbox.js';

Expand Down 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);
this.updateIonicClasses();
}

@HostListener('ionChange', ['$event.target'])
Expand Down
4 changes: 2 additions & 2 deletions packages/angular/src/standalone/directives/toggle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
forwardRef,
} from '@angular/core';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
import { ValueAccessor, setIonicClasses } from '@ionic/angular/common';
import { ValueAccessor } from '@ionic/angular/common';
import type { ToggleChangeEventDetail, Components } from '@ionic/core/components';
import { defineCustomElement } from '@ionic/core/components/ion-toggle.js';

Expand Down Expand Up @@ -62,7 +62,7 @@ export class IonToggle extends ValueAccessor {

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

@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,88 @@
import { test, expect } from '@playwright/test';

// The classes come from the control state, so opting into Angular's `ng-*` classes must not change them.
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 mark a field as pending, not valid or invalid, while async validation is running', async ({ page }) => {
const username = page.locator('ion-input#username');

await expect(username).toHaveClass(/\bion-pending\b/);
await expect(username).not.toHaveClass(/\bion-valid\b/);
await expect(username).not.toHaveClass(/\bion-invalid\b/);
});

test('should remove the pending class after async validation finishes', async ({ page }) => {
const username = page.locator('ion-input#username');

await expect(username).toHaveClass(/\bion-pending\b/);

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

await expect(username).toHaveClass(/\bion-valid\b/);
await expect(username).not.toHaveClass(/\bion-pending\b/);
});
});
}
Loading
Loading