[英]Jest toHaveBeenCalled is not able to watch the called method
I am writing unit tests for an Angular application.我正在为 Angular 应用程序编写单元测试。 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:在规范文件中,我为 fetchURLService > getMetadataFromUrl 方法创建了一个存根:
class URLServiceStub {
getMetadataFromUrl(url: string) {
return undefined;
}
}
I am providing this class inside of TestBed:我在 TestBed 中提供这个 class:
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 the if
check.我认为您需要确保
fileUrl
表单值有一个值,因为它很可能在if
检查中没有 go。
Try this:尝试这个:
it('should call getMetadataFromUrl()', fakeAsync(() => {
const mockMetadataFromUrl = 'testMetaData';
const getMetadataFromUrlSpy = jest
.spyOn(URLService , 'getMetadataFromUrl')
.mockReturnValue(of(mockMetadataFromUrl));
// !! set a value
component.componentForm.get('fileUrl').setValue('abc');
fixture.detectChanges();
component.onUrlEntry();
// !! wait for the subscription to finish (could be optional)
tick();
expect(getMetadataFromUrlSpy).toHaveBeenCalled();
}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.