Skip to content

feat(tooltip/testing): add test harness for mat-tooltip #19144

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
May 26, 2020
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
6 changes: 6 additions & 0 deletions src/cdk/testing/protractor/protractor-element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,12 @@ export class ProtractorElement implements TestElement {
.perform();
}

async mouseAway(): Promise<void> {
return browser.actions()
.mouseMove(await this.element.getWebElement(), {x: -1, y: -1})
.perform();
}

async sendKeys(...keys: (string | TestKey)[]): Promise<void>;
async sendKeys(modifiers: ModifierKeys, ...keys: (string | TestKey)[]): Promise<void>;
async sendKeys(...modifiersAndKeys: any[]): Promise<void> {
Expand Down
3 changes: 3 additions & 0 deletions src/cdk/testing/test-element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,9 @@ export interface TestElement {
/** Hovers the mouse over the element. */
hover(): Promise<void>;

/** Moves the mouse away from the element. */
mouseAway(): Promise<void>;

/**
* Sends the given string to the input as a series of key presses. Also fires input events
* and attempts to add the string to the Element's value.
Expand Down
6 changes: 6 additions & 0 deletions src/cdk/testing/testbed/unit-test-element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,12 @@ export class UnitTestElement implements TestElement {
await this._stabilize();
}

async mouseAway(): Promise<void> {
await this._stabilize();
dispatchMouseEvent(this.element, 'mouseleave');
await this._stabilize();
}

async sendKeys(...keys: (string | TestKey)[]): Promise<void>;
async sendKeys(modifiers: ModifierKeys, ...keys: (string | TestKey)[]): Promise<void>;
async sendKeys(...modifiersAndKeys: any[]): Promise<void> {
Expand Down
8 changes: 4 additions & 4 deletions src/cdk/testing/tests/test-main-component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ import {
templateUrl: 'test-main-component.html',
host: {
'[class.hovering]': '_isHovering',
'(mouseenter)': 'onMouseOver()',
'(mouseout)': 'onMouseOut()',
'(mouseenter)': 'onMouseEnter()',
'(mouseleave)': 'onMouseLeave()',
},
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
Expand All @@ -50,11 +50,11 @@ export class TestMainComponent implements OnDestroy {

private _fakeOverlayElement: HTMLElement;

onMouseOver() {
onMouseEnter() {
this._isHovering = true;
}

onMouseOut() {
onMouseLeave() {
this._isHovering = false;
}

Expand Down
12 changes: 12 additions & 0 deletions src/cdk/testing/tests/testbed.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,18 @@ describe('TestbedHarnessEnvironment', () => {
expect(classAttr).toContain('hovering');
});

it('should be able to stop hovering', async () => {
const host = await harness.host();
let classAttr = await host.getAttribute('class');
expect(classAttr).not.toContain('hovering');
await host.hover();
classAttr = await host.getAttribute('class');
expect(classAttr).toContain('hovering');
await host.mouseAway();
classAttr = await host.getAttribute('class');
expect(classAttr).not.toContain('hovering');
});

it('should be able to getAttribute', async () => {
const memoStr = `
This is an example that shows how to use component harness
Expand Down
1 change: 1 addition & 0 deletions src/material/config.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ entryPoints = [
"tabs/testing",
"toolbar",
"tooltip",
"tooltip/testing",
"tree",
"form-field/testing",
"form-field/testing/control",
Expand Down
50 changes: 50 additions & 0 deletions src/material/tooltip/testing/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
load("//tools:defaults.bzl", "ng_test_library", "ng_web_test_suite", "ts_library")

package(default_visibility = ["//visibility:public"])

ts_library(
name = "testing",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
module_name = "@angular/material/tooltip/testing",
deps = [
"//src/cdk/testing",
],
)

filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)

ng_test_library(
name = "harness_tests_lib",
srcs = ["shared.spec.ts"],
deps = [
":testing",
"//src/cdk/testing",
"//src/cdk/testing/testbed",
"//src/material/tooltip",
"@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/tooltip",
],
)

ng_web_test_suite(
name = "unit_tests",
deps = [":unit_tests_lib"],
)
9 changes: 9 additions & 0 deletions src/material/tooltip/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';
10 changes: 10 additions & 0 deletions src/material/tooltip/testing/public-api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* @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 './tooltip-harness';
export * from './tooltip-harness-filters';
67 changes: 67 additions & 0 deletions src/material/tooltip/testing/shared.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import {HarnessLoader} from '@angular/cdk/testing';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {Component} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {MatTooltipModule} from '@angular/material/tooltip';
import {MatTooltipHarness} from '@angular/material/tooltip/testing/tooltip-harness';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';

/** Shared tests to run on both the original and MDC-based tooltips. */
export function runHarnessTests(
tooltipModule: typeof MatTooltipModule, tooltipHarness: typeof MatTooltipHarness) {
let fixture: ComponentFixture<TooltipHarnessTest>;
let loader: HarnessLoader;

beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [tooltipModule, NoopAnimationsModule],
declarations: [TooltipHarnessTest],
}).compileComponents();

fixture = TestBed.createComponent(TooltipHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
});

it('should load all tooltip harnesses', async () => {
const tooltips = await loader.getAllHarnesses(tooltipHarness);
expect(tooltips.length).toBe(2);
});

it('should be able to show a tooltip', async () => {
const tooltip = await loader.getHarness(tooltipHarness.with({selector: '#one'}));
expect(await tooltip.isOpen()).toBe(false);
await tooltip.show();
expect(await tooltip.isOpen()).toBe(true);
});

it('should be able to hide a tooltip', async () => {
const tooltip = await loader.getHarness(tooltipHarness.with({selector: '#one'}));
expect(await tooltip.isOpen()).toBe(false);
await tooltip.show();
expect(await tooltip.isOpen()).toBe(true);
await tooltip.hide();
expect(await tooltip.isOpen()).toBe(false);
});

it('should be able to get the text of a tooltip', async () => {
const tooltip = await loader.getHarness(tooltipHarness.with({selector: '#one'}));
await tooltip.show();
expect(await tooltip.getTooltipText()).toBe('Tooltip message');
});

it('should return empty when getting the tooltip text while closed', async () => {
const tooltip = await loader.getHarness(tooltipHarness.with({selector: '#one'}));
expect(await tooltip.getTooltipText()).toBe('');
});
}

@Component({
template: `
<button [matTooltip]="message" id="one">Trigger 1</button>
<button matTooltip="Static message" id="two">Trigger 2</button>
`
})
class TooltipHarnessTest {
message = 'Tooltip message';
}
12 changes: 12 additions & 0 deletions src/material/tooltip/testing/tooltip-harness-filters.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/**
* @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';

/** A set of criteria that can be used to filter a list of `MatTooltipHarness` instances. */
export interface TooltipHarnessFilters extends BaseHarnessFilters {}
7 changes: 7 additions & 0 deletions src/material/tooltip/testing/tooltip-harness.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import {MatTooltipModule} from '@angular/material/tooltip';
import {runHarnessTests} from '@angular/material/tooltip/testing/shared.spec';
import {MatTooltipHarness} from './tooltip-harness';

describe('Non-MDC-based MatTooltipHarness', () => {
runHarnessTests(MatTooltipModule, MatTooltipHarness);
});
49 changes: 49 additions & 0 deletions src/material/tooltip/testing/tooltip-harness.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/**
* @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, HarnessPredicate} from '@angular/cdk/testing';
import {TooltipHarnessFilters} from './tooltip-harness-filters';

/** Harness for interacting with a standard mat-tooltip in tests. */
export class MatTooltipHarness extends ComponentHarness {
private _optionalPanel = this.documentRootLocatorFactory().locatorForOptional('.mat-tooltip');
static hostSelector = '.mat-tooltip-trigger';

/**
* Gets a `HarnessPredicate` that can be used to search
* for a tooltip trigger with specific attributes.
* @param options Options for narrowing the search.
* @return a `HarnessPredicate` configured with the given options.
*/
static with(options: TooltipHarnessFilters = {}): HarnessPredicate<MatTooltipHarness> {
return new HarnessPredicate(MatTooltipHarness, options);
}

/** Shows the tooltip. */
async show(): Promise<void> {
return (await this.host()).hover();
}

/** Hides the tooltip. */
async hide(): Promise<void> {
const host = await this.host();
await host.mouseAway();
await this.forceStabilize(); // Needed in order to flush the `hide` animation.
}

/** Gets whether the tooltip is open. */
async isOpen(): Promise<boolean> {
return !!(await this._optionalPanel());
}

/** Gets a promise for the tooltip panel's text. */
async getTooltipText(): Promise<string> {
const panel = await this._optionalPanel();
return panel ? panel.text() : '';
}
}
4 changes: 3 additions & 1 deletion src/material/tooltip/tooltip.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,9 @@ export function MAT_TOOLTIP_DEFAULT_OPTIONS_FACTORY(): MatTooltipDefaultOptions
@Directive({
selector: '[matTooltip]',
exportAs: 'matTooltip',
host: {
'class': 'mat-tooltip-trigger'
}
})
export class MatTooltip implements OnDestroy, OnInit {
_overlayRef: OverlayRef | null;
Expand Down Expand Up @@ -331,7 +334,6 @@ export class MatTooltip implements OnDestroy, OnInit {
}

const overlayRef = this._createOverlay();

this._detach();
this._portal = this._portal || new ComponentPortal(TooltipComponent, this._viewContainerRef);
this._tooltipInstance = overlayRef.attach(this._portal).instance;
Expand Down
1 change: 1 addition & 0 deletions tools/public_api_guard/cdk/testing.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ export interface TestElement {
hover(): Promise<void>;
isFocused(): Promise<boolean>;
matchesSelector(selector: string): Promise<boolean>;
mouseAway(): Promise<void>;
sendKeys(...keys: (string | TestKey)[]): Promise<void>;
sendKeys(modifiers: ModifierKeys, ...keys: (string | TestKey)[]): Promise<void>;
text(): Promise<string>;
Expand Down
1 change: 1 addition & 0 deletions tools/public_api_guard/cdk/testing/protractor.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export declare class ProtractorElement implements TestElement {
hover(): Promise<void>;
isFocused(): Promise<boolean>;
matchesSelector(selector: string): Promise<boolean>;
mouseAway(): Promise<void>;
sendKeys(...keys: (string | TestKey)[]): Promise<void>;
sendKeys(modifiers: ModifierKeys, ...keys: (string | TestKey)[]): Promise<void>;
text(): Promise<string>;
Expand Down
1 change: 1 addition & 0 deletions tools/public_api_guard/cdk/testing/testbed.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export declare class UnitTestElement implements TestElement {
hover(): Promise<void>;
isFocused(): Promise<boolean>;
matchesSelector(selector: string): Promise<boolean>;
mouseAway(): Promise<void>;
sendKeys(...keys: (string | TestKey)[]): Promise<void>;
sendKeys(modifiers: ModifierKeys, ...keys: (string | TestKey)[]): Promise<void>;
text(): Promise<string>;
Expand Down
11 changes: 11 additions & 0 deletions tools/public_api_guard/material/tooltip/testing.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export declare class MatTooltipHarness extends ComponentHarness {
getTooltipText(): Promise<string>;
hide(): Promise<void>;
isOpen(): Promise<boolean>;
show(): Promise<void>;
static hostSelector: string;
static with(options?: TooltipHarnessFilters): HarnessPredicate<MatTooltipHarness>;
}

export interface TooltipHarnessFilters extends BaseHarnessFilters {
}