Angular unit testing relative RouterLinks

Discussão em 'Angular' iniciado por Chris Barr, Maio 13, 2025.

  1. Chris Barr

    Chris Barr Guest

    In my Angular app I need to be able to unit test that routerLink create the correct href attribute. Sometimes they are links relative to the current route, and sometimes they are absolute links from the root.

    I am only able to successfully test the absolute links. When I attempt to test the relative links it just shows the href value as '/'

    In my component template I do this

    @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>
    }
    }


    And in my *.spec.ts file I have

    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);
    });

    //This test FAILS with "Expected '/' to equal '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');
    });

    //This test PASSES
    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');
    });
    });


    StackBlitz Demo

    Continue reading...

Compartilhe esta Página