UNPKG

14.9 kBJavaScriptView Raw
1import { TestKey, getNoKeysSpecifiedError, _getTextWithExcludedElements, HarnessEnvironment } from '@angular/cdk/testing';
2import * as webdriver from 'selenium-webdriver';
3
4/**
5 * Maps the `TestKey` constants to WebDriver's `webdriver.Key` constants.
6 * See https://github.com/SeleniumHQ/selenium/blob/trunk/javascript/webdriver/key.js#L29
7 */
8const seleniumWebDriverKeyMap = {
9 [TestKey.BACKSPACE]: webdriver.Key.BACK_SPACE,
10 [TestKey.TAB]: webdriver.Key.TAB,
11 [TestKey.ENTER]: webdriver.Key.ENTER,
12 [TestKey.SHIFT]: webdriver.Key.SHIFT,
13 [TestKey.CONTROL]: webdriver.Key.CONTROL,
14 [TestKey.ALT]: webdriver.Key.ALT,
15 [TestKey.ESCAPE]: webdriver.Key.ESCAPE,
16 [TestKey.PAGE_UP]: webdriver.Key.PAGE_UP,
17 [TestKey.PAGE_DOWN]: webdriver.Key.PAGE_DOWN,
18 [TestKey.END]: webdriver.Key.END,
19 [TestKey.HOME]: webdriver.Key.HOME,
20 [TestKey.LEFT_ARROW]: webdriver.Key.ARROW_LEFT,
21 [TestKey.UP_ARROW]: webdriver.Key.ARROW_UP,
22 [TestKey.RIGHT_ARROW]: webdriver.Key.ARROW_RIGHT,
23 [TestKey.DOWN_ARROW]: webdriver.Key.ARROW_DOWN,
24 [TestKey.INSERT]: webdriver.Key.INSERT,
25 [TestKey.DELETE]: webdriver.Key.DELETE,
26 [TestKey.F1]: webdriver.Key.F1,
27 [TestKey.F2]: webdriver.Key.F2,
28 [TestKey.F3]: webdriver.Key.F3,
29 [TestKey.F4]: webdriver.Key.F4,
30 [TestKey.F5]: webdriver.Key.F5,
31 [TestKey.F6]: webdriver.Key.F6,
32 [TestKey.F7]: webdriver.Key.F7,
33 [TestKey.F8]: webdriver.Key.F8,
34 [TestKey.F9]: webdriver.Key.F9,
35 [TestKey.F10]: webdriver.Key.F10,
36 [TestKey.F11]: webdriver.Key.F11,
37 [TestKey.F12]: webdriver.Key.F12,
38 [TestKey.META]: webdriver.Key.META,
39};
40/** Gets a list of WebDriver `Key`s for the given `ModifierKeys`. */
41function getSeleniumWebDriverModifierKeys(modifiers) {
42 const result = [];
43 if (modifiers.control) {
44 result.push(webdriver.Key.CONTROL);
45 }
46 if (modifiers.alt) {
47 result.push(webdriver.Key.ALT);
48 }
49 if (modifiers.shift) {
50 result.push(webdriver.Key.SHIFT);
51 }
52 if (modifiers.meta) {
53 result.push(webdriver.Key.META);
54 }
55 return result;
56}
57
58/** A `TestElement` implementation for WebDriver. */
59class SeleniumWebDriverElement {
60 constructor(element, _stabilize) {
61 this.element = element;
62 this._stabilize = _stabilize;
63 }
64 /** Blur the element. */
65 async blur() {
66 await this._executeScript((element) => element.blur(), this.element());
67 await this._stabilize();
68 }
69 /** Clear the element's input (for input and textarea elements only). */
70 async clear() {
71 await this.element().clear();
72 await this._stabilize();
73 }
74 async click(...args) {
75 await this._dispatchClickEventSequence(args, webdriver.Button.LEFT);
76 await this._stabilize();
77 }
78 async rightClick(...args) {
79 await this._dispatchClickEventSequence(args, webdriver.Button.RIGHT);
80 await this._stabilize();
81 }
82 /** Focus the element. */
83 async focus() {
84 await this._executeScript((element) => element.focus(), this.element());
85 await this._stabilize();
86 }
87 /** Get the computed value of the given CSS property for the element. */
88 async getCssValue(property) {
89 await this._stabilize();
90 return this.element().getCssValue(property);
91 }
92 /** Hovers the mouse over the element. */
93 async hover() {
94 await this._actions().mouseMove(this.element()).perform();
95 await this._stabilize();
96 }
97 /** Moves the mouse away from the element. */
98 async mouseAway() {
99 await this._actions().mouseMove(this.element(), { x: -1, y: -1 }).perform();
100 await this._stabilize();
101 }
102 async sendKeys(...modifiersAndKeys) {
103 const first = modifiersAndKeys[0];
104 let modifiers;
105 let rest;
106 if (first !== undefined && typeof first !== 'string' && typeof first !== 'number') {
107 modifiers = first;
108 rest = modifiersAndKeys.slice(1);
109 }
110 else {
111 modifiers = {};
112 rest = modifiersAndKeys;
113 }
114 const modifierKeys = getSeleniumWebDriverModifierKeys(modifiers);
115 const keys = rest
116 .map(k => (typeof k === 'string' ? k.split('') : [seleniumWebDriverKeyMap[k]]))
117 .reduce((arr, k) => arr.concat(k), [])
118 // webdriver.Key.chord doesn't work well with geckodriver (mozilla/geckodriver#1502),
119 // so avoid it if no modifier keys are required.
120 .map(k => (modifierKeys.length > 0 ? webdriver.Key.chord(...modifierKeys, k) : k));
121 // Throw an error if no keys have been specified. Calling this function with no
122 // keys should not result in a focus event being dispatched unexpectedly.
123 if (keys.length === 0) {
124 throw getNoKeysSpecifiedError();
125 }
126 await this.element().sendKeys(...keys);
127 await this._stabilize();
128 }
129 /**
130 * Gets the text from the element.
131 * @param options Options that affect what text is included.
132 */
133 async text(options) {
134 await this._stabilize();
135 if (options?.exclude) {
136 return this._executeScript(_getTextWithExcludedElements, this.element(), options.exclude);
137 }
138 // We don't go through the WebDriver `getText`, because it excludes text from hidden elements.
139 return this._executeScript((element) => (element.textContent || '').trim(), this.element());
140 }
141 /**
142 * Sets the value of a `contenteditable` element.
143 * @param value Value to be set on the element.
144 */
145 async setContenteditableValue(value) {
146 const contenteditableAttr = await this.getAttribute('contenteditable');
147 if (contenteditableAttr !== '' && contenteditableAttr !== 'true') {
148 throw new Error('setContenteditableValue can only be called on a `contenteditable` element.');
149 }
150 await this._stabilize();
151 return this._executeScript((element, valueToSet) => (element.textContent = valueToSet), this.element(), value);
152 }
153 /** Gets the value for the given attribute from the element. */
154 async getAttribute(name) {
155 await this._stabilize();
156 return this._executeScript((element, attribute) => element.getAttribute(attribute), this.element(), name);
157 }
158 /** Checks whether the element has the given class. */
159 async hasClass(name) {
160 await this._stabilize();
161 const classes = (await this.getAttribute('class')) || '';
162 return new Set(classes.split(/\s+/).filter(c => c)).has(name);
163 }
164 /** Gets the dimensions of the element. */
165 async getDimensions() {
166 await this._stabilize();
167 const { width, height } = await this.element().getSize();
168 const { x: left, y: top } = await this.element().getLocation();
169 return { width, height, left, top };
170 }
171 /** Gets the value of a property of an element. */
172 async getProperty(name) {
173 await this._stabilize();
174 return this._executeScript((element, property) => element[property], this.element(), name);
175 }
176 /** Sets the value of a property of an input. */
177 async setInputValue(newValue) {
178 await this._executeScript((element, value) => (element.value = value), this.element(), newValue);
179 await this._stabilize();
180 }
181 /** Selects the options at the specified indexes inside of a native `select` element. */
182 async selectOptions(...optionIndexes) {
183 await this._stabilize();
184 const options = await this.element().findElements(webdriver.By.css('option'));
185 const indexes = new Set(optionIndexes); // Convert to a set to remove duplicates.
186 if (options.length && indexes.size) {
187 // Reset the value so all the selected states are cleared. We can
188 // reuse the input-specific method since the logic is the same.
189 await this.setInputValue('');
190 for (let i = 0; i < options.length; i++) {
191 if (indexes.has(i)) {
192 // We have to hold the control key while clicking on options so that multiple can be
193 // selected in multi-selection mode. The key doesn't do anything for single selection.
194 await this._actions().keyDown(webdriver.Key.CONTROL).perform();
195 await options[i].click();
196 await this._actions().keyUp(webdriver.Key.CONTROL).perform();
197 }
198 }
199 await this._stabilize();
200 }
201 }
202 /** Checks whether this element matches the given selector. */
203 async matchesSelector(selector) {
204 await this._stabilize();
205 return this._executeScript((element, s) => (Element.prototype.matches || Element.prototype.msMatchesSelector).call(element, s), this.element(), selector);
206 }
207 /** Checks whether the element is focused. */
208 async isFocused() {
209 await this._stabilize();
210 return webdriver.WebElement.equals(this.element(), this.element().getDriver().switchTo().activeElement());
211 }
212 /**
213 * Dispatches an event with a particular name.
214 * @param name Name of the event to be dispatched.
215 */
216 async dispatchEvent(name, data) {
217 await this._executeScript(dispatchEvent, name, this.element(), data);
218 await this._stabilize();
219 }
220 /** Gets the webdriver action sequence. */
221 _actions() {
222 return this.element().getDriver().actions();
223 }
224 /** Executes a function in the browser. */
225 async _executeScript(script, ...var_args) {
226 return this.element()
227 .getDriver()
228 .executeScript(script, ...var_args);
229 }
230 /** Dispatches all the events that are part of a click event sequence. */
231 async _dispatchClickEventSequence(args, button) {
232 let modifiers = {};
233 if (args.length && typeof args[args.length - 1] === 'object') {
234 modifiers = args.pop();
235 }
236 const modifierKeys = getSeleniumWebDriverModifierKeys(modifiers);
237 // Omitting the offset argument to mouseMove results in clicking the center.
238 // This is the default behavior we want, so we use an empty array of offsetArgs if
239 // no args remain after popping the modifiers from the args passed to this function.
240 const offsetArgs = (args.length === 2 ? [{ x: args[0], y: args[1] }] : []);
241 let actions = this._actions().mouseMove(this.element(), ...offsetArgs);
242 for (const modifierKey of modifierKeys) {
243 actions = actions.keyDown(modifierKey);
244 }
245 actions = actions.click(button);
246 for (const modifierKey of modifierKeys) {
247 actions = actions.keyUp(modifierKey);
248 }
249 await actions.perform();
250 }
251}
252/**
253 * Dispatches an event with a particular name and data to an element. Note that this needs to be a
254 * pure function, because it gets stringified by WebDriver and is executed inside the browser.
255 */
256function dispatchEvent(name, element, data) {
257 const event = document.createEvent('Event');
258 event.initEvent(name);
259 // tslint:disable-next-line:ban Have to use `Object.assign` to preserve the original object.
260 Object.assign(event, data || {});
261 element.dispatchEvent(event);
262}
263
264/** The default environment options. */
265const defaultEnvironmentOptions = {
266 queryFn: async (selector, root) => root().findElements(webdriver.By.css(selector)),
267};
268/**
269 * This function is meant to be executed in the browser. It taps into the hooks exposed by Angular
270 * and invokes the specified `callback` when the application is stable (no more pending tasks).
271 */
272function whenStable(callback) {
273 Promise.all(window.frameworkStabilizers.map(stabilizer => new Promise(stabilizer))).then(callback);
274}
275/**
276 * This function is meant to be executed in the browser. It checks whether the Angular framework has
277 * bootstrapped yet.
278 */
279function isBootstrapped() {
280 return !!window.frameworkStabilizers;
281}
282/** Waits for angular to be ready after the page load. */
283async function waitForAngularReady(wd) {
284 await wd.wait(() => wd.executeScript(isBootstrapped));
285 await wd.executeAsyncScript(whenStable);
286}
287/** A `HarnessEnvironment` implementation for WebDriver. */
288class SeleniumWebDriverHarnessEnvironment extends HarnessEnvironment {
289 constructor(rawRootElement, options) {
290 super(rawRootElement);
291 this._options = { ...defaultEnvironmentOptions, ...options };
292 this._stabilizeCallback = () => this.forceStabilize();
293 }
294 /** Gets the ElementFinder corresponding to the given TestElement. */
295 static getNativeElement(el) {
296 if (el instanceof SeleniumWebDriverElement) {
297 return el.element();
298 }
299 throw Error('This TestElement was not created by the WebDriverHarnessEnvironment');
300 }
301 /** Creates a `HarnessLoader` rooted at the document root. */
302 static loader(driver, options) {
303 return new SeleniumWebDriverHarnessEnvironment(() => driver.findElement(webdriver.By.css('body')), options);
304 }
305 /**
306 * Flushes change detection and async tasks captured in the Angular zone.
307 * In most cases it should not be necessary to call this manually. However, there may be some edge
308 * cases where it is needed to fully flush animation events.
309 */
310 async forceStabilize() {
311 await this.rawRootElement().getDriver().executeAsyncScript(whenStable);
312 }
313 /** @docs-private */
314 async waitForTasksOutsideAngular() {
315 // TODO: figure out how we can do this for the webdriver environment.
316 // https://github.com/angular/components/issues/17412
317 }
318 /** Gets the root element for the document. */
319 getDocumentRoot() {
320 return () => this.rawRootElement().getDriver().findElement(webdriver.By.css('body'));
321 }
322 /** Creates a `TestElement` from a raw element. */
323 createTestElement(element) {
324 return new SeleniumWebDriverElement(element, this._stabilizeCallback);
325 }
326 /** Creates a `HarnessLoader` rooted at the given raw element. */
327 createEnvironment(element) {
328 return new SeleniumWebDriverHarnessEnvironment(element, this._options);
329 }
330 // Note: This seems to be working, though we may need to re-evaluate if we encounter issues with
331 // stale element references. `() => Promise<webdriver.WebElement[]>` seems like a more correct
332 // return type, though supporting it would require changes to the public harness API.
333 /**
334 * Gets a list of all elements matching the given selector under this environment's root element.
335 */
336 async getAllRawElements(selector) {
337 const els = await this._options.queryFn(selector, this.rawRootElement);
338 return els.map((x) => () => x);
339 }
340}
341
342export { SeleniumWebDriverElement, SeleniumWebDriverHarnessEnvironment, waitForAngularReady };
343//# sourceMappingURL=selenium-webdriver.mjs.map