You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Playwright JavaScript校验API响应中的指定多属性对象

如何校验API响应数组中存在指定对象(完全匹配)

你的问题出在直接拿整个API响应对象和单个预期对象做匹配——API返回的是包含UserTypes数组的外层对象,而你要找的是数组里的某个元素,结构完全不匹配,所以toMatchObject和toEqual都失效了。

正确的解决方案

方案1:用expect.arrayContaining做数组包含校验

先提取响应里的UserTypes数组,再用arrayContaining结合toEqual检查数组中是否存在完全匹配的对象:

const responseBody = await getAllUserTypes.json();
// 预期对象
const expectedObject = {
    "UserTypeId": 3,
    "UserType": "Support Agent"
};

expect(responseBody.UserTypes).toEqual(
  expect.arrayContaining([expectedObject])
);

这个写法会严格检查数组中是否存在一个和expectedObject所有属性、值完全一致的元素,符合你“完全匹配”的要求。

方案2:先查找元素再断言

如果想更清晰地定位元素,也可以先用find找到对应ID的对象,再做完全匹配断言:

const responseBody = await getAllUserTypes.json();
const expectedObject = {
    "UserTypeId": 3,
    "UserType": "Support Agent"
};

const targetUserType = responseBody.UserTypes.find(type => type.UserTypeId === expectedObject.UserTypeId);
// 断言找到的对象和预期完全一致
expect(targetUserType).toEqual(expectedObject);

如果数组里找不到ID为3的对象,targetUserType会是undefined,断言直接失败,同时能确保找到的对象属性完全符合预期。

为什么原来的代码无效?

你原来的代码是把整个响应体({UserTypes: [...]})和单个用户类型对象({UserTypeId:3,...})做匹配,两者结构完全不同:外层对象只有UserTypes一个属性,而预期对象是数组中的元素,自然匹配失败。

内容的提问来源于stack exchange,提问作者Praveen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 15:52:15