[英]How to write unit test for method in Angular component using jasmine?
I am new to jasmine unit test, but I'm not sure how to write and how it works in jasmine. Really facing lots of error.我是 jasmine 单元测试的新手,但我不确定如何编写以及它在 jasmine 中的工作方式。真的面临很多错误。
Can anyone help me to write a unit test for the below code?谁能帮我为下面的代码编写单元测试?
app.component.html app.component.html
<a href="" class="black" id="upload-template" (click)="uploadTemplate($event)" style="position: relative">
<img style="width: 45px" src="/assets/images/icons/upload (1).png" alt="upload the model" />
<div>Upload Template</div>
<i *ngIf="uploadTempStatus" class="fas fa-check-circle fa-2x upload-check" aria-hidden="true"></i>
</a>
app.component.ts应用程序组件.ts
uploadTemplate(e) {
e.preventDefault();
this.clearMsg();
if (this.selectedModel == null) {
this.messageService.add({ severity: 'error', summary: 'Please option from dropdown', detail: 'Please contact Admin', sticky: true });
} else if (this.selectedModel.name == 'Classification') {
this.router.navigate(['router_one'], { state: { data: this.selectedModel } });
} else {
this.router.navigate(['router_two'], { state: { data: this.selectedModel } });
}
}
spec file规格文件
function newEvent(eventName: string) {
const event = document.createEvent('CustomEvent');
event.initCustomEvent(eventName, false, false, null);
return event;
}
it('should be ok uploadTemplate', async(() => {
const uploadT = fixture.debugElement.query(By.css('#upload-template'));
expect(uploadT).toBeDefined();
const uploadTNativeElement = uploadT.nativeElement;
expect(uploadTNativeElement).toBeDefined();
fixture.detectChanges();
uploadTNativeElement.dispatchEvent(newEvent('click'));
//uploadTNativeElement.dispatchEvent(new Event('click'));
fixture.detectChanges();
fixture.whenStable().then(() => {
spyOn(component, 'uploadTemplate').and.callThrough();
expect(component.uploadTemplate).toHaveBeenCalled();
});
}));
error: Expected spy uploadTemplate to have been called.错误:预期间谍 uploadTemplate 已被调用。
The spy on component method uploadTemplate
must be created before the click event is dispatched.监听组件方法
uploadTemplate
必须在派发点击事件之前创建。 Try to change the unit test as follows:尝试更改单元测试如下:
it('should be ok uploadTemplate', async(() => {
...
spyOn(component, 'uploadTemplate').and.callThrough();
uploadTNativeElement.dispatchEvent(newEvent('click'));
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(component.uploadTemplate).toHaveBeenCalled();
});
}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.