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

Angular单元测试:相对RouterLinks生成正确href的问题

解决Angular路由相对链接单元测试href显示为'/'的问题

问题场景

在Angular应用中测试routerLink生成的href属性时,绝对链接测试正常通过,但相对链接的href始终返回'/',导致测试失败。

组件模板代码

@for (item of dataService.list; track item.id){
  @if (item.documents.length === 1) {
    <a [routerLink]="['/', 'documents', item.documents[0].id]">{{ item.id }} (Single)</a>
  } @else {
    <a [routerLink]="item.id">{{ item.id }} (Multiple)</a>
  }
}

原测试代码

describe('AppComponent', () => {
  let fixture: ComponentFixture<AppComponent>;
  let mockDataService: DataService;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [AppComponent],
      providers: [provideRouter([]), { provide: ActivatedRoute, useValue: {} }],
    }).compileComponents();

    fixture = TestBed.createComponent(AppComponent);
    mockDataService = TestBed.inject(DataService);
  });

  //测试失败:预期为'One',实际为'/'
  it('should use a relative link when there are multiple documents', () => {
    spyOnProperty(mockDataService, 'list', 'get').and.returnValue([
      { id: 'One', documents: [{ id: '1' }, { id: '2' }] },
    ]);
    fixture.detectChanges();

    const linkEl = fixture.debugElement.query(By.css('a')).nativeElement;

    expect(linkEl.getAttribute('href')).toEqual('One');
  });

  //测试通过
  it('should use an absolute link when there is only one document', () => {
    spyOnProperty(mockDataService, 'list').and.returnValue([
      { id: 'Two', documents: [{ id: '3' }] },
    ]);
    fixture.detectChanges();

    const linkEl = fixture.debugElement.query(By.css('a')).nativeElement;

    expect(linkEl.getAttribute('href')).toEqual('/documents/3');
  });
});

问题原因

相对路由的解析依赖ActivatedRoute提供的当前路由上下文,原测试中仅传入空对象作为ActivatedRoute的模拟值,缺少url、routeConfig等必要属性,导致Router无法正确计算相对路径,默认返回根路径'/'。同时,原测试预期的'One'不符合Angular路由的实际行为——根路径下的相对链接会被解析为/[相对路径]。

解决方案

  1. 给ActivatedRoute提供包含基础路由状态的模拟值,确保Router能正确解析相对路径;
  2. 修正测试预期值,匹配Angular路由生成的实际href格式。

修改后的测试代码

import { BehaviorSubject } from 'rxjs';
import { UrlSegment } from '@angular/router';

describe('AppComponent', () => {
  let fixture: ComponentFixture<AppComponent>;
  let mockDataService: DataService;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [AppComponent],
      providers: [
        provideRouter([]), 
        { 
          provide: ActivatedRoute, 
          useValue: {
            // 模拟当前路由为空路径
            url: new BehaviorSubject<UrlSegment[]>([]).asObservable(),
            routeConfig: { path: '' }
          } 
        }
      ],
    }).compileComponents();

    fixture = TestBed.createComponent(AppComponent);
    mockDataService = TestBed.inject(DataService);
  });

  it('should use a relative link when there are multiple documents', () => {
    spyOnProperty(mockDataService, 'list', 'get').and.returnValue([
      { id: 'One', documents: [{ id: '1' }, { id: '2' }] },
    ]);
    fixture.detectChanges();

    const linkEl = fixture.debugElement.query(By.css('a')).nativeElement;

    // 根路径下的相对链接会生成/One
    expect(linkEl.getAttribute('href')).toEqual('/One');
  });

  it('should use an absolute link when there is only one document', () => {
    spyOnProperty(mockDataService, 'list').and.returnValue([
      { id: 'Two', documents: [{ id: '3' }] },
    ]);
    fixture.detectChanges();

    const linkEl = fixture.debugElement.query(By.css('a')).nativeElement;

    expect(linkEl.getAttribute('href')).toEqual('/documents/3');
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 03:15:18