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

Angular单元测试如何修改Mock ActivatedRoute的queryParams参数值

解决方案

单场景直接修改方式

如果你只需要单独编写admin-mismatch场景的测试用例,直接把Mock ActivatedRoute配置中queryParams的type字段值从'mismatch'改为'admin-mismatch'即可,修改后的完整配置如下:

await TestBed.configureTestingModule({
    declarations: [ErrorPageComponent],
    imports: [GraphQLModule, RouterTestingModule],
    providers: [
        Apollo,
        {
            provide: ActivatedRoute,
            useValue: {
                queryParams: of({
                    name: 'John Doe',
                    cacheKey: 'cacheKey',
                    type: 'admin-mismatch'
                })
            }
        },
    ]
}).compileComponents();

beforeEach(() => {
    fixture = TestBed.createComponent(ErrorPageComponent);
    component = fixture.componentInstance;
    route = TestBed.inject(ActivatedRoute);
    fixture.detectChanges();
});

多场景复用优化方案(推荐)

如果你需要同时覆盖mismatch、admin-mismatch等多种type场景的测试,无需重复编写TestBed配置,可以用RxJS的Subject实现动态传参:

// 顶层引入并定义Subject用于动态控制queryParams
import { Subject } from 'rxjs';
const queryParamsSubject = new Subject();

await TestBed.configureTestingModule({
    declarations: [ErrorPageComponent],
    imports: [GraphQLModule, RouterTestingModule],
    providers: [
        Apollo,
        {
            provide: ActivatedRoute,
            useValue: {
                queryParams: queryParamsSubject.asObservable()
            }
        },
    ]
}).compileComponents();

beforeEach(() => {
    fixture = TestBed.createComponent(ErrorPageComponent);
    component = fixture.componentInstance;
    route = TestBed.inject(ActivatedRoute);
    fixture.detectChanges();
});

// 不同测试用例传入对应参数即可
it('should handle mismatch scenario', () => {
  queryParamsSubject.next({
    name: 'John Doe',
    cacheKey: 'cacheKey',
    type: 'mismatch'
  });
  fixture.detectChanges();
  // 此处编写对应测试逻辑
});

it('should handle admin-mismatch scenario', () => {
  queryParamsSubject.next({
    name: 'John Doe',
    cacheKey: 'cacheKey',
    type: 'admin-mismatch'
  });
  fixture.detectChanges();
  // 此处编写对应测试逻辑
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 12:57:02