【问题标题】:How to get element attribute value in webdriverio using typescript with await syntax?如何使用带有等待语法的打字稿在 webdriverio 中获取元素属性值?
【发布时间】:2017-11-07 19:24:06
【问题描述】:
主题
更多信息:
以下代码示例无法编译:
let id = (await browser.element(selector)).getAttribute('id');
TSError: ⨯ 无法编译 TypeScript ...: 属性 'getAttribute'
'RawResult' 类型上不存在。 (2339)
let id = (await browser.element(selector).getAttribute('id'));
TSError: ⨯ 无法编译 TypeScript ...: 'await' 操作数的类型
必须是有效的承诺,或者不能包含可调用的 'then'
成员。 (1320)
【问题讨论】:
标签:
typescript
async-await
webdriver-io
【解决方案1】:
我真的不知道为什么,但 webdriverio 定义声明了 an object that looks like a promise but is called Client。
在 TypeScript 中,您可以使用返回 Promise 的 await 函数。您可以使用自己的函数和承诺包装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);
})();
【解决方案2】:
实际上,如果您的 wdio 在同步模式下运行,这非常简单 - 所以不需要任何 async/await:
it('get attribute', () => {
browser.url('')
let classes = browser.element('html').getAttribute('class')
console.warn('ATRRIBUTE CLASS IS:', classes)
})
您的 classes 变量将是简单的字符串对象。
只需确保您在配置中设置了属性同步: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,