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

Angular Jasmine单元测试报异步函数5000ms未完成错误解决方案

Jasmine单元测试超时问题解决方案

报错根因

触发Async function did not complete within 5000ms (Jasmine)错误的核心原因是测试代码存在3处逻辑缺陷:

  • 调用getAll()发起的HTTP测试请求未被拦截返回模拟响应,返回的Observable始终处于pending状态,subscribe内的断言和done()回调永远不会执行,Jasmine等待超时后抛出错误。
  • beforeEach块存在冗余无效代码:多余包裹了waitForAsync(async () => {})(块内无异步操作,不需要异步包装),先通过jasmine.createSpyObj创建service实例后又被TestBed注入的实例覆盖,无实际作用。
  • 未提供DisbursementService依赖的AppConfigServicemock实现,TestBed初始化服务时会因依赖缺失抛出注入错误。

修正后的完整测试代码

import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
// 以下导入路径替换为你项目的实际文件路径
import { DisbursementService } from './disbursement.service';
import { AppConfigService } from 'src/app/core/services/app-config.service';
import { MockData } from 'src/app/test/mock-data';

describe('DisbursementService', () => {
  let httpTestingController: HttpTestingController;
  let disbService: DisbursementService;
  // 模拟配置服务返回的固定测试API地址
  const mockAppConfig = {
    settings: {
      apiUrl: 'https://test-api.mocksite.com'
    }
  };

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [
        DisbursementService,
        // 注入mock版AppConfigService,解决依赖注入报错
        { provide: AppConfigService, useValue: mockAppConfig }
      ]
    });
    httpTestingController = TestBed.inject(HttpTestingController);
    disbService = TestBed.inject(DisbursementService);
  });

  it('getAll 方法应返回符合预期的DisbursementGridDto数组', () => {
    const expectedData = MockData.createDisbursementGridDtoList();

    disbService.getAll().subscribe(data => {
      expect(data.length).toEqual(expectedData.length);
      expect(data).toEqual(expectedData);
    });

    // 拦截对应地址的GET请求
    const targetReq = httpTestingController.expectOne(`${mockAppConfig.settings.apiUrl}/Disbursement/GetAll`);
    // 校验请求方法正确
    expect(targetReq.request.method).toEqual('GET');
    // 推送模拟响应,同步触发subscribe逻辑
    targetReq.flush(expectedData);
  });

  afterEach(() => {
    // 校验不存在未处理的多余请求
    httpTestingController.verify();
  });
});

关键修正点说明

  • 移除冗余逻辑:删掉不必要的waitForAsync异步包装、无效的spy service创建代码,TestBed注入服务为同步操作,无需额外异步等待。
  • 补全依赖mock:通过TestBed的providers配置注入mock实现的AppConfigService,返回固定测试API前缀,解决服务初始化时的依赖注入报错。
  • 正确使用Angular HTTP测试能力:调用服务方法后通过HttpTestingController拦截目标请求,调用flush()同步返回模拟数据,不需要手动编写done回调标记异步完成,从根源解决超时问题。
  • 增加测试严谨性校验:验证请求方法、请求地址符合预期,测试结束后校验无多余未处理请求,避免测试逻辑漏测。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 04:06:06