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

Jasmine测试框架如何校验接口响应结果包含指定字段与对应值

问题说明

需要校验接口响应中是否包含值为wuihduwih的postText字段,以及值为60f469cf784379051298e96d的userId字段。

接口返回响应结构

({ 
  id: '612bf0792ca01806398da2d6', 
  data: Object({ 
    createdOn: '2021-08-29T20:39:21.445Z', 
    lastUpdatedBy: null, 
    userId: '60f469cf784379051298e96d', 
    displayName: 'Nadia', 
    postText: 'wuihduwih', 
    postImages: [  ], 
    pluginInstance: Object({ 
      pluginInstanceId: '1627334094776-047554258642281355', 
      pluginInstanceTitle: 'communityFeedPlugin' 
    }), 
    isPublic: false, 
    _buildfire: Object({ 
      index: Object({ 
        array1: [ 
          Object({ string1: 'userId_60f469cf784379051298e96d' }), 
          Object({ string1: 'displayName_nadia' }), 
          Object({ string1: 'pluginTitle_communityfeedplugin' }), 
          Object({ string1: 'isPublic_0' }) 
        ] 
      }) 
    }) 
  }), 
  tag: 'posts' 
})

原有错误测试用例

执行失败的Jasmine用例如下:

Posts.addPost({postText :'wuihduwih'},(err,resp) => {
  expect(resp).toContain(jasmine.objectContaining({
      postText :'wuihduwih'
    }));
  done();
});
正确写法

用例失败有两个核心原因:

  • toContain是Jasmine专门用于校验数组是否包含指定元素的匹配器,不能用于对象属性校验
  • 目标字段postText和userId都嵌套在响应的data属性下,不属于响应根级属性

两种可选的正确写法如下:

嵌套对象匹配写法

Posts.addPost({postText :'wuihduwih'},(err,resp) => {
  expect(resp).toEqual(jasmine.objectContaining({
    data: jasmine.objectContaining({
      postText: 'wuihduwih',
      userId: '60f469cf784379051298e96d'
    })
  }));
  done();
});

直接属性校验写法

Posts.addPost({postText :'wuihduwih'},(err,resp) => {
  expect(resp.data.postText).toBe('wuihduwih');
  expect(resp.data.userId).toBe('60f469cf784379051298e96d');
  done();
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 17:30:06