如何使用带有等待语法的typescript获取webdriverio中的元素属性值?

时间:2017-06-06 16:55:15

标签: typescript async-await webdriver-io

SUBJ。

更多信息:

以下代码示例无法编译:

let id = (await browser.element(selector)).getAttribute('id');
  

TSError:⨯无法编译TypeScript ...:属性'getAttribute'   在'RawResult'类型中不存在。 (2339)

let id = (await browser.element(selector).getAttribute('id'));
  

TSError:⨯无法编译TypeScript ...:'await'操作数的类型   必须是有效的承诺或不得包含可调用的'然后'   会员。 (1320)

2 个答案:

答案 0 :(得分:0)

我不知道为什么,但webdriverio定义声明an object that looks like a promise but is called Client

在TypeScript中,您可以await返回Promise的函数。您可以使用自己的函数和承诺包装webdriverio API:

import * as webdriverio from "webdriverio";

function getTitleAsync(url: string) {
    return new Promise((resolve, reject) => {
        const options = { desiredCapabilities: { browserName: "chrome" } };
        const client = webdriverio.remote(options);
        client
            .init()
            .url(url)
            .getTitle()
            .then(function (title) {
                resolve(title);
            })
            .end();
    });
}

然后你可以等待你的功能:

(async () => {
    const title = await getTitleAsync("https://duckduckgo.com/");
    console.log(title);
})();

答案 1 :(得分:0)

实际上,如果您的wdio以同步模式运行,这非常简单 - 所以不需要任何async / await:

it('get attribute', () => {
    browser.url('')
    let classes = browser.element('html').getAttribute('class')
    console.warn('ATRRIBUTE CLASS IS:', classes)
})

您的classes变量将是简单的字符串对象。

只需确保在config中设置属性sync:true:

// Per default WebdriverIO commands getting executed in a synchronous way using
// the wdio-sync package. If you still want to run your tests in an async way
// using promises you can set the sync command to false.
sync: true,