Skip to content

Commit

Permalink
FI-1498 feat: pressKey can receive selector
Browse files Browse the repository at this point in the history
  • Loading branch information
uid11 committed Oct 29, 2024
1 parent b042b43 commit 0ae2c51
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 6 deletions.
65 changes: 59 additions & 6 deletions src/actions/pressKey.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,73 @@
import {LogEventType} from '../constants/internal';
import {getPlaywrightPage} from '../useContext';
import {E2edError} from '../utils/error';
import {log} from '../utils/log';
import {getDescriptionFromSelector} from '../utils/selectors';

import type {Keyboard} from '@playwright/test';
import type {KeyboardPressKey, Selector} from '../types/internal';

import type {KeyboardPressKey} from '../types/internal';
type Options = Readonly<{delay?: number; timeout?: number}>;

type Options = Parameters<Keyboard['press']>[1];
type PressKey = ((
this: void,
selector: Selector,
key: KeyboardPressKey,
options?: Options,
) => Promise<void>) &
((this: void, key: KeyboardPressKey, options?: Options) => Promise<void>);

/**
* Presses the specified keyboard keys.
*/
export const pressKey = async (key: KeyboardPressKey, options: Options = {}): Promise<void> => {
log(`Press keyboard key: "${key}"`, options, LogEventType.InternalAction);
export const pressKey: PressKey = async (
keyOrSelector: KeyboardPressKey | Selector,
keyOrOptions?: KeyboardPressKey | Options,
maybeOptions?: Options,
): Promise<void> => {
let key: KeyboardPressKey;
let selector: Selector | undefined;
let options: Options;

if (typeof keyOrSelector === 'string') {
key = keyOrSelector;

if (typeof keyOrOptions === 'string') {
throw new E2edError('keyOrOptions is string', {
keyOrOptions,
keyOrSelector,
maybeOptions,
});
}

options = keyOrOptions ?? {};
} else {
selector = keyOrSelector;

if (typeof keyOrOptions !== 'string') {
throw new E2edError('keyOrOptions is not string', {
keyOrOptions,
keyOrSelector,
maybeOptions,
});
}

key = keyOrOptions;

options = maybeOptions ?? {};
}

const withDescription =
selector !== undefined
? ` on element with description ${getDescriptionFromSelector(selector)}`
: '';

log(`Press keyboard key${withDescription}: "${key}"`, options, LogEventType.InternalAction);

const page = getPlaywrightPage();

await page.keyboard.press(key, options);
if (selector !== undefined) {
await selector.getPlaywrightLocator().press(key, options);
} else {
await page.keyboard.press(key, options);
}
};
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"noImplicitReturns": true,
"noPropertyAccessFromIndexSignature": true,
"noUncheckedIndexedAccess": true,
"noUncheckedSideEffectImports": true,
"noUnusedLocals": true,
"outDir": "build",
"paths": {
Expand Down

0 comments on commit 0ae2c51

Please sign in to comment.