Playwright测试:异步函数返回值获取问题及代码修复求助
修复Playwright测试中async函数返回值获取问题
你的问题核心是async函数调用时未正确使用await,导致拿到的是Promise对象而非实际的密码值。以下是具体修复方案:
问题分析
createNewPassword是async函数,直接调用this.createNewPassword()会返回一个Promise,而不是你需要的密码字符串。虽然你在fill时用了await new_login_password,但这不是规范写法,且前期的变量存储和日志打印都会出错。
修复后的代码
// 建议把faker导入放在文件顶部,避免每次函数调用都重新require import { faker } from "@faker-js/faker"; async createNewPassword(email: string) { const password = faker.internet.password(); await this.forgot_password_email_field.fill(email); // 原代码中email_field变量未使用,可删除 await this.forgot_password_field.fill(password); // 直接用生成的password即可,无需从输入框取值,减少异步操作 const new_password = password; await this.forgot_password_confirm_field.fill(new_password); await this.forgot_password_save_button.click(); console.log(new_password); return new_password; } async loginNewPassword(email: string) { // 关键:调用async函数必须用await获取实际返回值 const new_login_password = await this.createNewPassword(email); console.log(new_login_password); // 若保存密码后需要跳转登录页,建议添加页面加载等待逻辑,比如await page.waitForURL('/login') await this.email_field.fill(email); await this.password_field.fill(new_login_password); await this.login_button.click(); }
额外优化点
- 删除冗余代码:原
createNewPassword中从输入框获取new_password完全多余,直接使用生成的password即可,减少一次不必要的异步操作。 - 提前导入依赖:将
@faker-js/faker的导入放在文件顶部,避免每次调用函数都重复加载模块,提升执行效率。 - 页面状态确认:点击保存密码按钮后,如果涉及页面跳转,建议添加等待页面加载完成的逻辑,确保登录相关元素已渲染再执行后续操作。
内容的提问来源于stack exchange,提问作者Josip Herceg
相关产品推荐
相关产品推荐

