Playwright+TypeScript调用API获取字段值返回undefined求助
问题排查:Playwright/TypeScript中API响应字段返回undefined
你的代码问题出在对API响应结构的访问方式错误。从你提供的响应示例可以看到,myJSON是一个数组(用[]包裹),但你直接通过responseBody.myJSON.myFIELD去访问字段——数组本身没有myFIELD这个属性,所以必然返回undefined。
1. 正确访问数组中的对象字段
因为你请求参数里设置了numrows:1,所以myJSON数组只会有一个元素,直接通过索引[0]访问数组第一个元素,再取myFIELD:
// 替换原来的断言 expect(responseBody.myJSON[0].myFIELD).toBeTruthy(); // 存储变量的正确写法 const myVAR = responseBody.myJSON[0].myFIELD; console.log(myVAR); // 现在会输出目标值
2. 额外优化建议
- 用
response.json()简化解析:Playwright的request对象提供了json()方法,无需手动调用text()和JSON.parse(),更简洁不易出错:const responseBody = await response.json(); // 替代原来的解析代码 - 增加数组非空断言:避免随机
offset导致API返回空数组的情况,提前校验:expect(responseBody.myJSON).not.toBeEmpty(); // 确保数组有元素 - TypeScript类型定义:给响应体添加类型,提前发现结构访问错误(新手可选,但长期能减少bug):
interface MyAPIResponse { myJSON: Array<{ myFIELD: string; TypeValue: string; Locality: string; Town: string; Status: string; }>; } // 解析时指定类型 const responseBody = await response.json() as MyAPIResponse;
修正后的完整代码
import { test, expect } from '@playwright/test' interface MyAPIResponse { myJSON: Array<{ myFIELD: string; TypeValue: string; Locality: string; Town: string; Status: string; }>; } test('API testing with a GET', async ({ request}) => { function myoffset(n){ return Math.floor(Math.random() * (n + 1)) }; const paras = {numrows: 1, offset: myoffset(400), TypeValue: 'TYPE', Locality: 'Place1', Town: 'Town1', Status: 'STAT'}; const myURL = 'https://myapi/url'; const response = await request.get(myURL, {params: paras }); expect(response.status()).toBe(200); const responseBody = await response.json() as MyAPIResponse; console.log(responseBody); // 先确保数组非空 expect(responseBody.myJSON).not.toBeEmpty(); // 正确访问目标字段 expect(responseBody.myJSON[0].myFIELD).toBeTruthy(); // 存储并打印变量 const myVAR = responseBody.myJSON[0].myFIELD; console.log('目标字段值:', myVAR); });
内容的提问来源于stack exchange,提问作者Adam Hartnett
相关产品推荐
相关产品推荐

