Selenium(Node.js)中使用getText获取元素文本的正确方法
Selenium + Mocha.js 获取元素文本问题解决办法
问题根源
updatedTimeValue是async函数,这类函数默认返回Promise对象,直接console.log(updatedTimeValue())打印的是未完成的Promise(pending状态),不是实际文本内容。- 你在函数内部用
.then()打印了文本,但外层又重复调用函数并打印Promise,导致输出混乱。
修正方案(推荐用async/await,更直观)
const updatedTimeValue = async () => { // 用await等待元素查找完成 const targetElement = await driver.findElement(By.className("MuiTypography-root jss1141 MuiTypography-body1")); // 用await等待文本获取完成 const elementText = await targetElement.getText(); console.log(elementText); return elementText; // 如需返回文本供其他逻辑使用 }; // 在Mocha测试中,测试函数必须定义为async,让Mocha等待异步操作完成 it('获取元素文本', async () => { await updatedTimeValue(); }); // 单独调用的话,要包裹在async自执行函数里 (async () => { await updatedTimeValue(); })();
另一种写法(纯.then(),不推荐混合async)
如果你习惯用.then(),可以去掉async关键字,统一用Promise链式调用:
const updatedTimeValue = () => { return driver.findElement(By.className("MuiTypography-root jss1141 MuiTypography-body1")) .getText() .then(text => { console.log(text); return text; }); }; // 直接调用即可,不要用console.log包裹函数调用 updatedTimeValue();
关键注意点
- Mocha测试里,所有包含异步操作的测试逻辑,必须让测试函数返回Promise,或者把测试函数定义为async(本质也是返回Promise),否则Mocha会提前结束测试,导致异步操作没完成就输出结果。
- 尽量统一异步写法,要么全用async/await,要么全用.then(),混合写法容易搞混异步流程。
内容的提问来源于stack exchange,提问作者Filip Kosmalla
相关产品推荐
相关产品推荐

