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="; 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()],
})pileComponents();
fixture = TestBed.createComponent(CustomSvgImagesComponent);
component = fixtureponentInstance;
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?