WebElement的getAttribute遇到问题

时间:2019-09-11 14:07:26

标签: typescript protractor

我正在尝试获取元素的属性。工作正常,但突然不行了。不知道我是否改变了什么。

错误:

TypeError: Cannot read property 'info' of undefined

方法1:

async getElementAttribute12(webElement: WebElement, whichAttribute: string): Promise<string> {
        try {
            let attribute = '';
            await webElement.getAttribute(whichAttribute).then(async function(attr) {
                await this.info('attr: ', attr);
                attribute = attr;
            });
            return attribute;
        } catch (error) {
            fail(`Get attribute error. ${error}`);
        }
    }

方法2:

检查元素是否存在之后。我认为这将是一个更好的方法。欢迎输入。

    async getElementAttribute(webElement: WebElement, whichAttribute: string): Promise<string> {
        try {
            let attribute = '';
            if (await browser.isElementPresent(webElement)) {
                await webElement.getAttribute(whichAttribute).then(async function(attr) {
                    await this.info('attr: ', attr);
                    attribute = attr;
                });
                return attribute;
            }

        } catch (error) {
            fail(`Get attribute error. ${error}`);
        }
    }

1 个答案:

答案 0 :(得分:1)

这里的问题是您的this指的是错误的东西,您需要在此处使用箭头功能:

await webElement.getAttribute(whichAttribute).then(async (attr) => {