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

Jest模拟Azure DevOps API响应后调用find方法报错的解决方法

问题:Jest模拟Azure DevOps API后find方法无法正确返回记录

代码场景

业务服务代码

const timeline = await buildClient.getBuildTimeline(project.id, buildId);

当前Jest模拟代码

jest.mock('azure-devops-extension-api', () => { return { getClient: (client: any) => new GitRestClient() }; });
export const mockGetItems = jest.fn().mockReturnValue({ records: [{ state: 2, type: 'TASK', task: { id: TASK_IDS[0] } }] });
class GitRestClient { 
  public getBuildTimeline(projectId: string, buildId: string): Promise<Timeline[]> { 
    return new Promise((resolve) => resolve(mockGetItems())); 
  } 
}

测试中出错的代码

const record = timeline.records.find((rec) => { return rec.type === 'Task'; });

问题分析

  1. 大小写不匹配:模拟数据中记录的type值为大写的'TASK',但测试代码中判断的是'Task'(首字母小写),导致find方法无法匹配到对应记录。
  2. 返回类型错误:getBuildTimeline的模拟返回类型声明为Promise<Timeline[]>(数组),但mockGetItems实际返回的是单个Timeline对象(包含records属性)。结合测试中直接调用timeline.records的逻辑,实际API应该返回单个对象而非数组,类型不匹配会导致timeline成为数组,调用timeline.records时直接报错。

修复后的模拟代码

jest.mock('azure-devops-extension-api', () => { return { getClient: (client: any) => new GitRestClient() }; });
export const mockGetItems = jest.fn().mockReturnValue({ records: [{ state: 2, type: 'Task', task: { id: TASK_IDS[0] } }] });
class GitRestClient { 
  // 修正返回类型为单个Timeline对象的Promise
  public getBuildTimeline(projectId: string, buildId: string): Promise<Timeline> { 
    return new Promise((resolve) => resolve(mockGetItems())); 
  } 
}

额外说明

如果实际Azure DevOps API的getBuildTimeline确实返回数组,需要调整业务代码和测试代码,遍历数组获取对应records;但根据现有测试逻辑,优先修正返回类型和type的大小写即可解决问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 17:35:25