开玩笑的tohavebeencalled无法观看所谓的方法
我正在为 Angular 应用程序编写单元测试。我尝试测试的方法如下:
onUrlEntry() {
const fileUrl = this.componentForm.get('fileUrl');
if(fileUrl?.value) {
this.URLService
.getMetadataFromUrl(fileUrl?.value)
.subscribe((metadataFileContent) => {
// ...
}, (err: HttpErrorResponse) => {
// ...
});
}
}
在规范文件中,我为 fetchURLService > 创建了一个存根。 getMetadataFromUrl 方法:
class URLServiceStub {
getMetadataFromUrl(url: string) {
return undefined;
}
}
我在 TestBed 内部提供此类:
providers: [
{ provide: URLService, useClass: URLServiceStub },
]
这是服务:
@Injectable({
providedIn: 'root',
})
export class URLService{
constructor(private httpClient: HttpClient) {}
getMetadataFromUrl(url: string) {
return this.httpClient.get(url, { responseType: 'text' });
}
}
现在进行单元测试:
it('should call getMetadataFromUrl()', fakeAsync(() => {
const mockMetadataFromUrl = 'testMetaData';
const getMetadataFromUrlSpy = jest
.spyOn(URLService , 'getMetadataFromUrl')
.mockReturnValue(of(mockMetadataFromUrl));
fixture.detectChanges();
component.onUrlEntry();
expect(getMetadataFromUrlSpy).toHaveBeenCalled();
}));
这没有执行。请帮帮我。
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您需要确保
fileUrl
表单值具有值,因为它很可能不会进入if
检查内部。试试这个:
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: