I am writing unit tests for an Angular application. The method I am trying to test is as follows:
onUrlEntry() {
const fileUrl = this.componentForm.get('fileUrl');
if(fileUrl?.value) {
this.URLService
.getMetadataFromUrl(fileUrl?.value)
.subscribe((metadataFileContent) => {
// ...
}, (err: HttpErrorResponse) => {
// ...
});
}
}
In the spec file, I have created a stub for the fetchURLService > getMetadataFromUrl method:
class URLServiceStub {
getMetadataFromUrl(url: string) {
return undefined;
}
}
I am providing this class inside of TestBed:
providers: [
{ provide: URLService, useClass: URLServiceStub },
]
Here's the Service:
@Injectable({
providedIn: 'root',
})
export class URLService{
constructor(private httpClient: HttpClient) {}
getMetadataFromUrl(url: string) {
return this.httpClient.get(url, { responseType: 'text' });
}
}
Now for the unit test:
it('should call getMetadataFromUrl()', fakeAsync(() => {
const mockMetadataFromUrl = 'testMetaData';
const getMetadataFromUrlSpy = jest
.spyOn(URLService , 'getMetadataFromUrl')
.mockReturnValue(of(mockMetadataFromUrl));
fixture.detectChanges();
component.onUrlEntry();
expect(getMetadataFromUrlSpy).toHaveBeenCalled();
}));
This is not executing. Please help me out.
Thanks!
I think you need to make sure
fileUrl
form value has a value because most likely it does not go inside of theif
check.Try this: