selenium-state-machine
Version:
Write Selenium tests using state machines
75 lines (74 loc) • 2.81 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebElementDependency = void 0;
const selenium_webdriver_1 = require("selenium-webdriver");
const Dependency_1 = require("./Dependency");
const Error_1 = require("./Error");
/**
* Specialized dependency type for WebElement objects. This object is responsible for
* handling stale state.
*/
class WebElementDependency extends Dependency_1.ValueDependency {
constructor(config) {
super(config);
this.invalidate = this.invalidate.bind(this);
this._debugElementInfo = this._value;
this._value = (this._value) ? (createWebElementProxy(this._value, this)) : (undefined);
}
set(v, provider) {
return this.clone({ value: createWebElementProxy(v, this), provider });
}
get value() {
if (this._value === undefined) {
throw new Error_1.CriticalError(`${this._name ? `[${this._name}] ` : ''}WebElementDependency not set.`);
}
return this._value;
}
get debugElement() {
return this._debugElementInfo;
}
clone(newValues) {
const dep = new WebElementDependency({
name: newValues?.name ?? this._name,
value: newValues?.value ?? this._value
});
dep.provider = newValues.provider;
return dep;
}
}
exports.WebElementDependency = WebElementDependency;
function createWebElementProxy(element, dependency) {
if (Object.getPrototypeOf(element)?.proxyed) {
return element;
}
const proxy = new Proxy(element, {
get(target, prop, receiver) {
const value = target[prop];
if (value instanceof Function) {
return function (...args) {
try {
const result = value.apply(this === receiver ? target : this, args);
if (selenium_webdriver_1.promise.isPromise(result) && 'catch' in result) {
return result.catch((e) => {
if (e instanceof selenium_webdriver_1.error.StaleElementReferenceError) {
dependency.invalidate();
}
throw e;
});
}
}
catch (e) {
if (e instanceof selenium_webdriver_1.error.StaleElementReferenceError) {
dependency.invalidate();
}
throw e;
}
};
}
return Reflect.get(target, prop, receiver);
},
});
const prototype = Object.getPrototypeOf(proxy);
prototype.proxyed = true;
return proxy;
}