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

Angular Observable单元测试:模拟API响应验证依赖项状态

Angular 依赖项展示逻辑单元测试方案

场景说明

需要针对员工依赖项的展示逻辑编写单元测试,模拟两种API响应场景:

  1. 所有依赖项的include字段为true
  2. 所有依赖项的include字段为false

步骤1:准备测试用配置数据

先定义两种场景的模拟API返回数据:

// 场景1:所有依赖项include为true
const allIncludedConfig = {
  employee_name: "SHubham",
  employee_dependents: [
    {name: "abc", include: true},
    {name: "xyz", include: true},
    {name: "ert", include: true},
  ]
};

// 场景2:所有依赖项include为false
const allExcludedConfig = {
  employee_name: "SHubham",
  employee_dependents: [
    {name: "abc", include: false},
    {name: "xyz", include: false},
    {name: "ert", include: false},
  ]
};

步骤2:配置测试模块与Mock服务

在测试文件中,通过TestBed替换真实的ConfigService为Mock版本,控制其返回的配置数据:

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { YourComponent } from './your.component'; // 替换为你的组件实际路径
import { ConfigService } from './config.service';
import { of } from 'rxjs';

describe('YourComponent', () => {
  let component: YourComponent;
  let fixture: ComponentFixture<YourComponent>;
  let mockConfigService: jasmine.SpyObj<ConfigService>;

  beforeEach(async () => {
    // 创建Mock的ConfigService,模拟configuration$属性
    mockConfigService = jasmine.createSpyObj('ConfigService', [], {
      configuration$: of({})
    });

    await TestBed.configureTestingModule({
      declarations: [YourComponent],
      providers: [
        { provide: ConfigService, useValue: mockConfigService }
      ]
    }).compileComponents();

    fixture = TestBed.createComponent(YourComponent);
    component = fixture.componentInstance;
  });

步骤3:编写对应场景的测试用例

测试场景1:所有依赖项include为true

it('should render all dependents when all include fields are true', () => {
  // 替换Mock服务的返回值为场景1数据
  mockConfigService.configuration$ = of(allIncludedConfig);
  // 触发组件变更检测
  fixture.detectChanges();

  // 假设组件用.dependent-item类渲染每个依赖项,断言渲染数量
  const dependentElements = fixture.nativeElement.querySelectorAll('.dependent-item');
  expect(dependentElements.length).toBe(3);
  // 可选:断言具体依赖项的内容
  expect(dependentElements[0].textContent).toContain('abc');
});

测试场景2:所有依赖项include为false

it('should not render any dependents when all include fields are false', () => {
  // 替换Mock服务的返回值为场景2数据
  mockConfigService.configuration$ = of(allExcludedConfig);
  fixture.detectChanges();

  const dependentElements = fixture.nativeElement.querySelectorAll('.dependent-item');
  // 断言没有依赖项被渲染
  expect(dependentElements.length).toBe(0);
});

补充:若需Mock底层API服务

如果ConfigService的loadDetails()依赖其他API服务,可直接Mock该底层服务来控制返回值:

// 假设底层API服务名为ApiService,包含loadDetails方法
const mockApiService = jasmine.createSpyObj('ApiService', ['loadDetails']);

// 在TestBed中注入Mock的ApiService
providers: [
  ConfigService,
  { provide: ApiService, useValue: mockApiService }
]

// 在测试用例中设置返回值
it('should render all dependents when all include fields are true', () => {
  mockApiService.loadDetails.and.returnValue(of(allIncludedConfig));
  fixture.detectChanges();
  // 后续断言逻辑同上
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 09:27:45