有没有办法从它的属性装饰器向属性的对象添加一个函数。我尝试这样做但无法在装饰器中获取属性对象的引用。 我正在使用 Intern js 版本 4 进行 UI 自动化项目。我已经实现了页面对象模型来这样做。我想在这里实现的是
- 将包含验证消息的div的xpath传递给的页面对象 通过属性装饰器的文本框。
- 在属性装饰器中,在文本框的页面对象中添加一个函数 从该 div 获取可见文本。
这是我到目前为止尝试过的:
客户端页面.ts
export class ClientPage extends AbstractSearchPage implements LandingPage {
@Validate({xpath: '//sumit/shrestha'})
public clientId: TextBox;
constructor(remote: any) {
super(remote)
this.clientId = new TextBox(remote,'//*[@id="clientId"]')
this.dataGrid = new DataGrid(remote, '//table[@id="Table"]')
this.searchBtn = '//*[@id="search"]';
}
getPageUrl(): string {
return '#/clients/clients'
};
}
文本框.ts
export class TextBox extends InputElement {
constructor(remote: any, locator: any) {
super(remote, locator);
}
async enterValue(input: string) {
await this.remote.findByXpath(this.locator).clearValue().type(input);
}
async clearValue() {
await this.remote.findByXpath(this.locator).clearValue()
// return Promise.resolve(this);
}
}
验证.ts
export function Validate(config: any) {
var remote = getRemote();
return function (target: Object, property: string | symbol) {
/*
// I thought target is reference to Textbox object but it refers to
// ClientPage object and even clientpage object here (target) shows only
// functions when doing console.log(target)
*/
console.log(config.xpath)
target.prototype.requiredFieldValidation = async function (): Promise<string> {
await target.enterValue('ddd')
await target.clearValue('ddd')
return await remote.findByXpath(config.xpath).getVisibleText();
}
}
}
最佳答案
target
是 ClientPage 的原型(prototype)。你应该学习装饰器是如何工作的。参见 my article (俄罗斯)例如。
如果要给对象添加功能,存储在字段中,有两种方法。
第一种方法 - 定义 get/set 访问器,当值分配给属性时,将函数添加到该值。
export function Validate(config: any) {
var remote = getRemote();
return function (target: Object, property: string | symbol) {
// Create get/set accessors for the property
let value;
let propertyDescription = {
get: function() {
return value;
},
set: function(textBox) {
value = textBox;
// When textBox assigned to property, add function to object
textBox.requiredFieldValidation = async function (): Promise<string> {
await this.enterValue('ddd')
await this.clearValue('ddd')
return await remote.findByXpath(config.xpath).getVisibleText();
}
},
configurable: true,
enumerable: true
};
Object.defineProperty(target, property, propertyDescription);
}
}
第二种方法,使用反射元数据获取属性类型(构造函数类),并在其原型(prototype)中定义函数。您可以在 example from the article 中找到使用反射元数据的示例.它使用类型信息来执行依赖注入(inject)。
关于javascript - 通过 typescript 中的属性装饰器向属性的对象添加一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48833605/