Skip to content

feat(cdk-experimental/testing): Improve keyboard event support in harnesses #16645

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 6 commits into from
Aug 12, 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
4 changes: 2 additions & 2 deletions src/cdk-experimental/dialog/dialog.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -308,8 +308,8 @@ describe('Dialog', () => {
let backdrop = overlayContainerElement.querySelector('.cdk-overlay-backdrop') as HTMLElement;
let container = overlayContainerElement.querySelector('cdk-dialog-container') as HTMLElement;
dispatchKeyboardEvent(document.body, 'keydown', A);
dispatchKeyboardEvent(document.body, 'keydown', A, backdrop);
dispatchKeyboardEvent(document.body, 'keydown', A, container);
dispatchKeyboardEvent(document.body, 'keydown', A, undefined, backdrop);
dispatchKeyboardEvent(document.body, 'keydown', A, undefined, container);

expect(spy).toHaveBeenCalledTimes(3);
}));
Expand Down
2 changes: 1 addition & 1 deletion src/cdk-experimental/popover-edit/popover-edit.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -484,7 +484,7 @@ describe('CDK Popover Edit', () => {

describe('arrow keys', () => {
const dispatchKey = (cell: HTMLElement, keyCode: number) =>
dispatchKeyboardEvent(cell, 'keydown', keyCode, cell);
dispatchKeyboardEvent(cell, 'keydown', keyCode, undefined, cell);

it('moves focus up/down/left/right and prevents default', () => {
const rowCells = getRowCells();
Expand Down
3 changes: 3 additions & 0 deletions src/cdk-experimental/testing/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ ng_module(
],
),
module_name = "@angular/cdk-experimental/testing",
deps = [
"//src/cdk/testing",
],
)

ng_web_test_suite(
Expand Down
1 change: 1 addition & 0 deletions src/cdk-experimental/testing/protractor/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ ts_library(
module_name = "@angular/cdk-experimental/testing/protractor",
deps = [
"//src/cdk-experimental/testing",
"//src/cdk/testing",
"@npm//protractor",
],
)
79 changes: 75 additions & 4 deletions src/cdk-experimental/testing/protractor/protractor-element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,61 @@
* found in the LICENSE file at https://angular.io/license
*/

import {browser, ElementFinder} from 'protractor';
import {TestElement} from '../test-element';
import {ModifierKeys} from '@angular/cdk/testing';
import {browser, ElementFinder, Key} from 'protractor';
import {TestElement, TestKey} from '../test-element';

/** Maps the `TestKey` constants to Protractor's `Key` constants. */
const keyMap = {
[TestKey.BACKSPACE]: Key.BACK_SPACE,
[TestKey.TAB]: Key.TAB,
[TestKey.ENTER]: Key.ENTER,
[TestKey.SHIFT]: Key.SHIFT,
[TestKey.CONTROL]: Key.CONTROL,
[TestKey.ALT]: Key.ALT,
[TestKey.ESCAPE]: Key.ESCAPE,
[TestKey.PAGE_UP]: Key.PAGE_UP,
[TestKey.PAGE_DOWN]: Key.PAGE_DOWN,
[TestKey.END]: Key.END,
[TestKey.HOME]: Key.HOME,
[TestKey.LEFT_ARROW]: Key.ARROW_LEFT,
[TestKey.UP_ARROW]: Key.ARROW_UP,
[TestKey.RIGHT_ARROW]: Key.ARROW_RIGHT,
[TestKey.DOWN_ARROW]: Key.ARROW_DOWN,
[TestKey.INSERT]: Key.INSERT,
[TestKey.DELETE]: Key.DELETE,
[TestKey.F1]: Key.F1,
[TestKey.F2]: Key.F2,
[TestKey.F3]: Key.F3,
[TestKey.F4]: Key.F4,
[TestKey.F5]: Key.F5,
[TestKey.F6]: Key.F6,
[TestKey.F7]: Key.F7,
[TestKey.F8]: Key.F8,
[TestKey.F9]: Key.F9,
[TestKey.F10]: Key.F10,
[TestKey.F11]: Key.F11,
[TestKey.F12]: Key.F12,
[TestKey.META]: Key.META
};

/** Converts a `ModifierKeys` object to a list of Protractor `Key`s. */
function toProtractorModifierKeys(modifiers: ModifierKeys): string[] {
const result: string[] = [];
if (modifiers.control) {
result.push(Key.CONTROL);
}
if (modifiers.alt) {
result.push(Key.ALT);
}
if (modifiers.shift) {
result.push(Key.SHIFT);
}
if (modifiers.meta) {
result.push(Key.META);
}
return result;
}

/** A `TestElement` implementation for Protractor. */
export class ProtractorElement implements TestElement {
Expand Down Expand Up @@ -39,8 +92,26 @@ export class ProtractorElement implements TestElement {
.perform();
}

async sendKeys(keys: string): Promise<void> {
return this.element.sendKeys(keys);
async sendKeys(...keys: (string | TestKey)[]): Promise<void>;
async sendKeys(modifiers: ModifierKeys, ...keys: (string | TestKey)[]): Promise<void>;
async sendKeys(...modifiersAndKeys: any[]): Promise<void> {
const first = modifiersAndKeys[0];
let modifiers: ModifierKeys;
let rest: (string | TestKey)[];
if (typeof first !== 'string' && typeof first !== 'number') {
modifiers = first;
rest = modifiersAndKeys.slice(1);
} else {
modifiers = {};
rest = modifiersAndKeys;
}

const modifierKeys = toProtractorModifierKeys(modifiers);
const keys = rest.map(k => typeof k === 'string' ? k.split('') : [keyMap[k]])
.reduce((arr, k) => arr.concat(k), [])
.map(k => Key.chord(...modifierKeys, k));

return this.element.sendKeys(...keys);
}

async text(): Promise<string> {
Expand Down
50 changes: 49 additions & 1 deletion src/cdk-experimental/testing/test-element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,48 @@
* found in the LICENSE file at https://angular.io/license
*/

/** Keyboard keys that do not result in input characters. */
import {ModifierKeys} from '@angular/cdk/testing';

/** An enum of non-text keys that can be used with the `sendKeys` method. */
// NOTE: This is a separate enum from `@angular/cdk/keycodes` because we don't necessarily want to
// support every possible keyCode. We also can't rely on Protractor's `Key` because we don't want a
// dependency on any particular testing framework here. Instead we'll just maintain this supported
// list of keys and let individual concrete `HarnessEnvironment` classes map them to whatever key
// representation is used in its respective testing framework.
export enum TestKey {
BACKSPACE,
TAB,
ENTER,
SHIFT,
CONTROL,
ALT,
ESCAPE,
PAGE_UP,
PAGE_DOWN,
END,
HOME,
LEFT_ARROW,
UP_ARROW,
RIGHT_ARROW,
DOWN_ARROW,
INSERT,
DELETE,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
META
}

/**
* This acts as a common interface for DOM elements across both unit and e2e tests. It is the
* interface through which the ComponentHarness interacts with the component's DOM.
Expand Down Expand Up @@ -33,7 +75,13 @@ export interface TestElement {
* 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.
*/
sendKeys(keys: string): Promise<void>;
sendKeys(...keys: (string | TestKey)[]): 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.
*/
sendKeys(modifiers: ModifierKeys, ...keys: (string | TestKey)[]): Promise<void>;

/** Gets the text from the element. */
text(): Promise<string>;
Expand Down
1 change: 1 addition & 0 deletions src/cdk-experimental/testing/testbed/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ ts_library(
module_name = "@angular/cdk-experimental/testing/testbed",
deps = [
"//src/cdk-experimental/testing",
"//src/cdk/keycodes",
"//src/cdk/testing",
"@npm//@angular/core",
],
Expand Down
71 changes: 46 additions & 25 deletions src/cdk-experimental/testing/testbed/unit-test-element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,51 @@
* found in the LICENSE file at https://angular.io/license
*/

import * as keyCodes from '@angular/cdk/keycodes';
import {
dispatchFakeEvent,
dispatchKeyboardEvent,
clearElement,
dispatchMouseEvent,
isTextInput,
ModifierKeys,
triggerBlur,
triggerFocus
triggerFocus,
typeInElement
} from '@angular/cdk/testing';
import {TestElement} from '../test-element';
import {TestElement, TestKey} from '../test-element';

function isTextInput(element: Element): element is HTMLInputElement | HTMLTextAreaElement {
return element.nodeName.toLowerCase() === 'input' ||
element.nodeName.toLowerCase() === 'textarea' ;
}
/** Maps `TestKey` constants to the `keyCode` and `key` values used by native browser events. */
const keyMap = {
[TestKey.BACKSPACE]: {keyCode: keyCodes.BACKSPACE, key: 'Backspace'},
[TestKey.TAB]: {keyCode: keyCodes.TAB, key: 'Tab'},
[TestKey.ENTER]: {keyCode: keyCodes.ENTER, key: 'Enter'},
[TestKey.SHIFT]: {keyCode: keyCodes.SHIFT, key: 'Shift'},
[TestKey.CONTROL]: {keyCode: keyCodes.CONTROL, key: 'Control'},
[TestKey.ALT]: {keyCode: keyCodes.ALT, key: 'Alt'},
[TestKey.ESCAPE]: {keyCode: keyCodes.ESCAPE, key: 'Escape'},
[TestKey.PAGE_UP]: {keyCode: keyCodes.PAGE_UP, key: 'PageUp'},
[TestKey.PAGE_DOWN]: {keyCode: keyCodes.PAGE_DOWN, key: 'PageDown'},
[TestKey.END]: {keyCode: keyCodes.END, key: 'End'},
[TestKey.HOME]: {keyCode: keyCodes.HOME, key: 'Home'},
[TestKey.LEFT_ARROW]: {keyCode: keyCodes.LEFT_ARROW, key: 'ArrowLeft'},
[TestKey.UP_ARROW]: {keyCode: keyCodes.UP_ARROW, key: 'ArrowUp'},
[TestKey.RIGHT_ARROW]: {keyCode: keyCodes.RIGHT_ARROW, key: 'ArrowRight'},
[TestKey.DOWN_ARROW]: {keyCode: keyCodes.DOWN_ARROW, key: 'ArrowDown'},
[TestKey.INSERT]: {keyCode: keyCodes.INSERT, key: 'Insert'},
[TestKey.DELETE]: {keyCode: keyCodes.DELETE, key: 'Delete'},
[TestKey.F1]: {keyCode: keyCodes.F1, key: 'F1'},
[TestKey.F2]: {keyCode: keyCodes.F2, key: 'F2'},
[TestKey.F3]: {keyCode: keyCodes.F3, key: 'F3'},
[TestKey.F4]: {keyCode: keyCodes.F4, key: 'F4'},
[TestKey.F5]: {keyCode: keyCodes.F5, key: 'F5'},
[TestKey.F6]: {keyCode: keyCodes.F6, key: 'F6'},
[TestKey.F7]: {keyCode: keyCodes.F7, key: 'F7'},
[TestKey.F8]: {keyCode: keyCodes.F8, key: 'F8'},
[TestKey.F9]: {keyCode: keyCodes.F9, key: 'F9'},
[TestKey.F10]: {keyCode: keyCodes.F10, key: 'F10'},
[TestKey.F11]: {keyCode: keyCodes.F11, key: 'F11'},
[TestKey.F12]: {keyCode: keyCodes.F12, key: 'F12'},
[TestKey.META]: {keyCode: keyCodes.META, key: 'Meta'}
};

/** A `TestElement` implementation for unit tests. */
export class UnitTestElement implements TestElement {
Expand All @@ -35,9 +67,7 @@ export class UnitTestElement implements TestElement {
if (!isTextInput(this.element)) {
throw Error('Attempting to clear an invalid element');
}
triggerFocus(this.element as HTMLElement);
this.element.value = '';
dispatchFakeEvent(this.element, 'input');
clearElement(this.element);
await this._stabilize();
}

Expand Down Expand Up @@ -66,21 +96,12 @@ export class UnitTestElement implements TestElement {
await this._stabilize();
}

async sendKeys(keys: string): Promise<void> {
async sendKeys(...keys: (string | TestKey)[]): Promise<void>;
async sendKeys(modifiers: ModifierKeys, ...keys: (string | TestKey)[]): Promise<void>;
async sendKeys(...modifiersAndKeys: any[]): Promise<void> {
await this._stabilize();
triggerFocus(this.element as HTMLElement);
for (const key of keys) {
const keyCode = key.charCodeAt(0);
dispatchKeyboardEvent(this.element, 'keydown', keyCode);
dispatchKeyboardEvent(this.element, 'keypress', keyCode);
if (isTextInput(this.element)) {
this.element.value += key;
}
dispatchKeyboardEvent(this.element, 'keyup', keyCode);
if (isTextInput(this.element)) {
dispatchFakeEvent(this.element, 'input');
}
}
const args = modifiersAndKeys.map(k => typeof k === 'number' ? keyMap[k as TestKey] : k);
typeInElement(this.element as HTMLElement, ...args);
await this._stabilize();
}

Expand Down
1 change: 1 addition & 0 deletions src/cdk-experimental/testing/tests/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ ng_module(
assets = glob(["**/*.html"]),
module_name = "@angular/cdk-experimental/testing/tests",
deps = [
"//src/cdk/keycodes",
"@npm//@angular/forms",
],
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
*/

import {ComponentHarness} from '../../component-harness';
import {TestElement} from '../../test-element';
import {TestElement, TestKey} from '../../test-element';
import {SubComponentHarness} from './sub-component-harness';

export class WrongComponentHarness extends ComponentHarness {
Expand Down Expand Up @@ -47,6 +47,7 @@ export class MainComponentHarness extends ComponentHarness {
readonly testLists = this.locatorForAll(SubComponentHarness.with({title: /test/}));
readonly requiredFourIteamToolsLists =
this.locatorFor(SubComponentHarness.with({title: 'List of test tools', itemCount: 4}));
readonly specaialKey = this.locatorFor('.special-key');

private _testTools = this.locatorFor(SubComponentHarness);

Expand All @@ -66,4 +67,12 @@ export class MainComponentHarness extends ComponentHarness {
const subComponent = await this._testTools();
return subComponent.getItems();
}

async sendEnter(): Promise<void> {
return (await this.input()).sendKeys(TestKey.ENTER);
}

async sendAltJ(): Promise<void> {
return (await this.input()).sendKeys({alt: true}, 'j');
}
}
12 changes: 12 additions & 0 deletions src/cdk-experimental/testing/tests/protractor.e2e.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,18 @@ describe('ProtractorHarnessEnvironment', () => {
const globalEl = await harness.globalEl();
expect(await globalEl.text()).toBe('I am a sibling!');
});

it('should send enter key', async () => {
const specialKey = await harness.specaialKey();
await harness.sendEnter();
expect(await specialKey.text()).toBe('enter');
});

it('should send alt+j key', async () => {
const specialKey = await harness.specaialKey();
await harness.sendAltJ();
expect(await specialKey.text()).toBe('alt-j');
});
});

describe('TestElement', () => {
Expand Down
3 changes: 2 additions & 1 deletion src/cdk-experimental/testing/tests/test-main-component.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ <h1 style="height: 50px">Main Component</h1>
<div id="asyncCounter">{{asyncCounter}}</div>
</div>
<div class="inputs">
<input [(ngModel)]="input" id="input" aria-label="input">
<input [(ngModel)]="input" id="input" aria-label="input" (keydown)="onKeyDown($event)">
<span class="special-key">{{specialKey}}</span>
<div id="value">Input: {{input}}</div>
<textarea id="memo" aria-label="memo">{{memo}}</textarea>
</div>
Expand Down
11 changes: 11 additions & 0 deletions src/cdk-experimental/testing/tests/test-main-component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/

import {ENTER} from '@angular/cdk/keycodes';
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Expand Down Expand Up @@ -35,6 +36,7 @@ export class TestMainComponent {
testTools: string[];
testMethods: string[];
_isHovering: boolean;
specialKey = '';

onMouseOver() {
this._isHovering = true;
Expand Down Expand Up @@ -64,4 +66,13 @@ export class TestMainComponent {
this._cdr.markForCheck();
}, 500);
}

onKeyDown(event: KeyboardEvent) {
if (event.keyCode === ENTER && event.key === 'Enter') {
this.specialKey = 'enter';
}
if (event.key === 'j' && event.altKey) {
this.specialKey = 'alt-j';
}
}
}
Loading