How to unit test multple HTTP requests in Angular?

Discussão em 'Angular' iniciado por Chris Barr, Janeiro 31, 2025.

  1. Chris Barr

    Chris Barr Guest

    I have a simple Angular 19 component that will make multiple requests for SVG files, and then insert them into a component

    @Component({
    selector: 'app-custom-svg-images',
    imports: [AsyncPipe],
    changeDetection: ChangeDetectionStrategy.OnPush,
    template: `<svg xmlns="http://www.w3.org/2000/svg" class="hidden-svg" [innerHTML]="svgSymbols$ | async"></svg>`,
    })
    export class CustomSvgImagesComponent {
    private readonly httpClient = inject(HttpClient);
    private readonly sanitizer = inject(DomSanitizer);

    private readonly svgFiles = ['logo', 'help', 'other-example'];

    public svgSymbols$ = forkJoin(
    this.svgFiles.map((fileName) => this.httpClient.get(`svgs/${fileName}.svg`, { responseType: 'text' })),
    ).pipe(
    map((svgContentArr) => {
    const preppedSvgs = svgContentArr.map((svgContent) => this.prepareSvg(svgContent));
    return this.sanitizer.bypassSecurityTrustHtml(preppedSvgs.join(''));
    }),
    );

    private prepareSvg(svgContent: string): string {
    return svgContent.replace(/<svg( xmlns=".+?")?( version=".+?")?/, '<symbol').replace('</svg>', '</symbol>');
    }
    }


    This works exactly how I want it to, however I am running into issues unit testing it.

    let component: CustomSvgImagesComponent;
    let fixture: ComponentFixture<CustomSvgImagesComponent>;
    let httpTestingController: HttpTestingController;

    beforeEach(async () => {
    await TestBed.configureTestingModule({
    imports: [CustomSvgImagesComponent],
    providers: [provideHttpClient(), provideHttpClientTesting()],
    }).compileComponents();

    fixture = TestBed.createComponent(CustomSvgImagesComponent);
    component = fixture.componentInstance;
    httpTestingController = TestBed.inject(HttpTestingController);
    });

    afterEach(() => {
    httpTestingController.verify();
    });

    it('should create', () => {
    fixture.detectChanges(); //triggers ngOnInit()

    expect(component).toBeTruthy();
    });

    it('should request all listed SVG file on load', () => {
    fixture.detectChanges(); //triggers ngOnInit()

    const req1 = httpTestingController.expectOne(`svgs/logo.svg`);
    req1.flush('<svg id="mock-logo"></svg>');

    const req2 = httpTestingController.expectOne(`svgs/help.svg`);
    req2.flush('<svg id="mock-help"></svg>');

    const req3 = httpTestingController.expectOne(`svgs/other-example.svg`);
    req3.flush('<svg id="mock-other"></svg>');
    });


    but I get this error:

    Error: Expected no open requests, found 3: GET svgs/logo.svg, GET svgs/help.svg, GET svgs/other-example.svg


    What am I doing wrong here and why do my HTTP requests not get called the way I expect them to?

    Continue reading...

Compartilhe esta Página