使用Playwright test.step包裹类方法后返回值丢失,测试报错
解决Playwright test.step包裹方法后无法返回结果的问题
问题核心是你的createUser方法没有返回test.step的执行结果,导致整个方法默认返回undefined,测试代码中自然无法读取user.phone。
修复代码
修改UserSteps类中的createUser方法,将test.step的返回值对外返回:
async createUser(data: CreateUserRequest): Promise<CreateUserSuccessResponse> { // 新增return,将test.step内部的user结果返回给调用方 return test.step(`Method Call /users with body: ${JSON.stringify(data)}`, async () => { const response = await this.integrationClient.post('users', { data }); const responseJson = await response.json(); const user = responseJson.result; this.userIdsToDelete.push(user.id); return user; }); }
额外优化说明
- 原代码中直接拼接
${data}会导致对象显示为[object Object],改用JSON.stringify(data)可以在Allure报告中展示完整的请求体内容,便于调试。 test.step本身返回Promise,直接return它与await后return效果一致,两种写法都可以:async createUser(data: CreateUserRequest): Promise<CreateUserSuccessResponse> { const user = await test.step(`Method Call /users with body: ${JSON.stringify(data)}`, async () => { const response = await this.integrationClient.post('users', { data }); const responseJson = await response.json(); const user = responseJson.result; this.userIdsToDelete.push(user.id); return user; }); return user; }
内容的提问来源于stack exchange,提问作者ROMAN SKRIPNIKOV
相关产品推荐
相关产品推荐

