Skip to content

feat(material-experimental): add test harness for form-field #17138

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

Merged
merged 1 commit into from
Sep 23, 2019
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
1 change: 1 addition & 0 deletions .github/CODEOWNERS
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@
# Material experimental package
/src/material-experimental/* @jelbourn
/src/material-experimental/input/** @devversion
/src/material-experimental/form-field/** @devversion
/src/material-experimental/mdc-autocomplete/** @crisbeto
/src/material-experimental/mdc-button/** @andrewseguin
/src/material-experimental/mdc-card/** @mmalerba
Expand Down
53 changes: 53 additions & 0 deletions src/material-experimental/form-field/testing/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package(default_visibility = ["//visibility:public"])

load("//tools:defaults.bzl", "ng_test_library", "ng_web_test_suite", "ts_library")

ts_library(
name = "testing",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
module_name = "@angular/material-experimental/form-field/testing",
deps = [
"//src/cdk/testing",
"//src/material-experimental/form-field/testing/control",
"//src/material-experimental/input/testing",
"//src/material-experimental/select/testing",
],
)

ng_test_library(
name = "harness_tests_lib",
srcs = ["shared.spec.ts"],
deps = [
":testing",
"//src/cdk/testing",
"//src/cdk/testing/testbed",
"@npm//@angular/forms",
"@npm//@angular/platform-browser",
],
)

ng_test_library(
name = "unit_tests_lib",
srcs = glob(
["**/*.spec.ts"],
exclude = ["shared.spec.ts"],
),
deps = [
":harness_tests_lib",
":testing",
"//src/material-experimental/input/testing",
"//src/material-experimental/select/testing",
"//src/material/autocomplete",
"//src/material/form-field",
"//src/material/input",
"//src/material/select",
],
)

ng_web_test_suite(
name = "unit_tests",
deps = [":unit_tests_lib"],
)
10 changes: 10 additions & 0 deletions src/material-experimental/form-field/testing/control/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package(default_visibility = ["//visibility:public"])

load("//tools:defaults.bzl", "ts_library")

ts_library(
name = "control",
srcs = glob(["**/*.ts"]),
module_name = "@angular/material-experimental/form-field/testing/control",
deps = ["//src/cdk/testing"],
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/

import {ComponentHarness} from '@angular/cdk/testing';

/**
* Base class for custom form-field control harnesses. Harnesses for
* custom controls with form-fields need to implement this interface.
*/
export abstract class MatFormFieldControlHarness extends ComponentHarness {}
9 changes: 9 additions & 0 deletions src/material-experimental/form-field/testing/control/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/

export * from './form-field-control-harness';
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/

import {BaseHarnessFilters} from '@angular/cdk/testing';

export interface FormFieldHarnessFilters extends BaseHarnessFilters {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import {MatInputHarness} from '@angular/material-experimental/input/testing';
import {MatSelectHarness} from '@angular/material-experimental/select/testing';
import {MatAutocompleteModule} from '@angular/material/autocomplete';
import {MatFormFieldModule} from '@angular/material/form-field';
import {MatInputModule} from '@angular/material/input';
import {MatSelectModule} from '@angular/material/select';

import {MatFormFieldHarness} from './form-field-harness';
import {runHarnessTests} from './shared.spec';

describe('Non-MDC-based MatFormFieldHarness', () => {
runHarnessTests(
[MatFormFieldModule, MatAutocompleteModule, MatInputModule, MatSelectModule],
MatFormFieldHarness, MatInputHarness, MatSelectHarness);
});
230 changes: 230 additions & 0 deletions src/material-experimental/form-field/testing/form-field-harness.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,230 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/

import {
ComponentHarness,
ComponentHarnessConstructor,
HarnessPredicate,
TestElement
} from '@angular/cdk/testing';
import {
MatFormFieldControlHarness
} from '@angular/material-experimental/form-field/testing/control';
import {MatInputHarness} from '@angular/material-experimental/input/testing';
import {MatSelectHarness} from '@angular/material-experimental/select/testing';
import {FormFieldHarnessFilters} from './form-field-harness-filters';

// TODO(devversion): support datepicker harness once developed (COMP-203).
// Also support chip list harness.
/** Possible harnesses of controls which can be bound to a form-field. */
export type FormFieldControlHarness = MatInputHarness|MatSelectHarness;
/**
* Harness for interacting with a standard Material form-field's in tests.
* @dynamic
*/
export class MatFormFieldHarness extends ComponentHarness {
static hostSelector = '.mat-form-field';

/**
* Gets a `HarnessPredicate` that can be used to search for an form-field with
* specific attributes.
* @param options Options for narrowing the search:
* - `selector` finds a form-field that matches the given selector.
* @return a `HarnessPredicate` configured with the given options.
*/
static with(options: FormFieldHarnessFilters = {}): HarnessPredicate<MatFormFieldHarness> {
return new HarnessPredicate(MatFormFieldHarness, options);
}

private _prefixContainer = this.locatorForOptional('.mat-form-field-prefix');
private _suffixContainer = this.locatorForOptional('.mat-form-field-suffix');
private _label = this.locatorForOptional('.mat-form-field-label');
private _errors = this.locatorForAll('.mat-error');
private _hints = this.locatorForAll('mat-hint,.mat-hint');

private _inputControl = this.locatorForOptional(MatInputHarness);
private _selectControl = this.locatorForOptional(MatSelectHarness);

/** Gets the appearance of the form-field. */
async getAppearance(): Promise<'legacy'|'standard'|'fill'|'outline'> {
const hostClasses = await (await this.host()).getAttribute('class');
if (hostClasses !== null) {
const appearanceMatch =
hostClasses.match(/mat-form-field-appearance-(legacy|standard|fill|outline)(?:$| )/);
if (appearanceMatch) {
return appearanceMatch[1] as 'legacy' | 'standard' | 'fill' | 'outline';
}
}
throw Error('Could not determine appearance of form-field.');
}

/**
* Gets the harness of the control that is bound to the form-field. Only
* default controls such as "MatInputHarness" and "MatSelectHarness" are
* supported.
*/
async getControl(): Promise<FormFieldControlHarness|null>;

/**
* Gets the harness of the control that is bound to the form-field. Searches
* for a control that matches the specified harness type.
*/
async getControl<X extends MatFormFieldControlHarness>(type: ComponentHarnessConstructor<X>):
Promise<X|null>;

/**
* Gets the harness of the control that is bound to the form-field. Searches
* for a control that matches the specified harness predicate.
*/
async getControl<X extends MatFormFieldControlHarness>(type: HarnessPredicate<X>):
Promise<X|null>;

// Implementation of the "getControl" method overload signatures.
async getControl<X extends MatFormFieldControlHarness>(type?: ComponentHarnessConstructor<X>|
HarnessPredicate<X>) {
if (type) {
return this.locatorForOptional(type)();
}
const hostEl = await this.host();
const [isInput, isSelect] = await Promise.all([
hostEl.hasClass('mat-form-field-type-mat-input'),
hostEl.hasClass('mat-form-field-type-mat-select'),
]);
if (isInput) {
return this._inputControl();
} else if (isSelect) {
return this._selectControl();
}
return null;
}

/** Whether the form-field has a label. */
async hasLabel(): Promise<boolean> {
return (await this.host()).hasClass('mat-form-field-has-label');
}

/** Gets the label of the form-field. */
async getLabel(): Promise<string|null> {
const labelEl = await this._label();
return labelEl ? labelEl.text() : null;
}

/** Whether the form-field has a floating label. */
async hasFloatingLabel(): Promise<boolean> {
return (await this.host()).hasClass('mat-form-field-can-float');
}

/** Whether the label is currently floating. */
async isLabelFloating(): Promise<boolean> {
return (await this.host()).hasClass('mat-form-field-should-float');
}

/** Whether the form-field is disabled. */
async isDisabled(): Promise<boolean> {
return (await this.host()).hasClass('mat-form-field-disabled');
}

/** Whether the form-field is currently autofilled. */
async isAutofilled(): Promise<boolean> {
return (await this.host()).hasClass('mat-form-field-autofilled');
}

/** Gets the theme color of the form-field. */
async getThemeColor(): Promise<'primary'|'accent'|'warn'> {
const hostEl = await this.host();
const [isAccent, isWarn] =
await Promise.all([hostEl.hasClass('mat-accent'), hostEl.hasClass('mat-warn')]);
if (isAccent) {
return 'accent';
} else if (isWarn) {
return 'warn';
}
return 'primary';
Copy link
Member

Choose a reason for hiding this comment

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

A bit more concise?

const hostClass = await (await this.host()).getAttribute('class');
for (const palette of ['accent', 'warn']) {
  if (hostClass.includes(palette)) {
    return palette;
  }
}

return 'primary';

Copy link
Member Author

Choose a reason for hiding this comment

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

Sounds like a good idea.

Copy link
Member Author

Choose a reason for hiding this comment

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

I'll actually keep it like that as otherwise we'd need to handle more things (i.e. spaces to separate classes in the class attribute). The current implementation is quite reasonable but just looks weird due to the Promise all for concurrency.

Copy link
Contributor

Choose a reason for hiding this comment

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

You could maybe use getProperty('classList') for this, now that we have separate methods for attributes and properties

Copy link
Member

Choose a reason for hiding this comment

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

I don't follow what you mean by handing more things. Checking for the absence/presence of "accent" or "warn" is enough, no?

Copy link
Member Author

Choose a reason for hiding this comment

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

My thinking is that class can contain more classes and that just checking using includes is not working 100%. e.g. class attribute could be: custom-mat-accent mat-primary-field.

So we need to ensure that there is a space before/after the class we check for, or that it is at the start/end of the class attribute value. or just split the class attribute by space.. Surely these cases are extremely rare but I don't think there is a benefit in making these things less robust if we can just simply use the public robust hasClass methods.

The current implementation basically checks for existence of the theme classes. It just uses the intended APIs but unfortunately looks kind of dirty (to me at least)

}

/** Gets error messages which are currently displayed in the form-field. */
async getErrorMessages(): Promise<string[]> {
return Promise.all((await this._errors()).map(e => e.text()));
}

/** Gets hint messages which are currently displayed in the form-field. */
async getHintMessages(): Promise<string[]> {
return Promise.all((await this._hints()).map(e => e.text()));
}

/**
* Gets a reference to the container element which contains all projected
* prefixes of the form-field.
*/
async getPrefixContainer(): Promise<TestElement|null> {
return this._prefixContainer();
}

/**
* Gets a reference to the container element which contains all projected
* suffixes of the form-field.
*/
async getSuffixContainer(): Promise<TestElement|null> {
return this._suffixContainer();
}

/**
* Whether the form control has been touched. Returns "null"
* if no form control is set up.
*/
async isControlTouched(): Promise<boolean|null> {
if (!await this._hasFormControl()) {
return null;
}
return (await this.host()).hasClass('ng-touched');
}

/**
* Whether the form control is dirty. Returns "null"
* if no form control is set up.
*/
async isControlDirty(): Promise<boolean|null> {
if (!await this._hasFormControl()) {
return null;
}
return (await this.host()).hasClass('ng-dirty');
}

/**
* Whether the form control is valid. Returns "null"
* if no form control is set up.
*/
async isControlValid(): Promise<boolean|null> {
if (!await this._hasFormControl()) {
return null;
}
return (await this.host()).hasClass('ng-valid');
}

/**
* Whether the form control is pending validation. Returns "null"
* if no form control is set up.
*/
async isControlPending(): Promise<boolean|null> {
if (!await this._hasFormControl()) {
return null;
}
return (await this.host()).hasClass('ng-pending');
}

/** Checks whether the form-field control has set up a form control. */
private async _hasFormControl(): Promise<boolean> {
const hostEl = await this.host();
// If no form "NgControl" is bound to the form-field control, the form-field
// is not able to forward any control status classes. Therefore if either the
// "ng-touched" or "ng-untouched" class is set, we know that it has a form control
const [isTouched, isUntouched] =
await Promise.all([hostEl.hasClass('ng-touched'), hostEl.hasClass('ng-untouched')]);
return isTouched || isUntouched;
}
}
9 changes: 9 additions & 0 deletions src/material-experimental/form-field/testing/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/

export * from './public-api';
15 changes: 15 additions & 0 deletions src/material-experimental/form-field/testing/public-api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/

// Re-export everything from the "form-field/testing/control" entry-point. To avoid
// circular dependencies, harnesses for default form-field controls (i.e. input, select)
// need to import the base form-field control harness through a separate entry-point.
export * from '@angular/material-experimental/form-field/testing/control';

export * from './form-field-harness';
export * from './form-field-harness-filters';
Loading