วิธีการเขียน unit test สำหรับ method ใน Angular component โดยใช้ดอกมะลิ

Sep 22 2020

ฉันยังใหม่กับการทดสอบหน่วยจัสมิน แต่ฉันไม่แน่ใจว่าจะเขียนอย่างไรและทำงานอย่างไรในจัสมิน ต้องเผชิญกับข้อผิดพลาดมากมายจริงๆ

ใครสามารถช่วยฉันเขียนการทดสอบหน่วยสำหรับรหัสด้านล่างนี้ได้หรือไม่

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

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 } });
    }

} 

ไฟล์ข้อมูลจำเพาะ

  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();
    });
  }));

ข้อผิดพลาด: คาดว่าจะมีการเรียกอัปโหลดเทมเพลตสปายแวร์

คำตอบ

1 uminder Sep 22 2020 at 12:23

uploadTemplateต้องสร้างวิธีการสอดแนมส่วนประกอบก่อนที่เหตุการณ์คลิกจะถูกส่งไป ลองเปลี่ยนการทดสอบหน่วยดังนี้:

it('should be ok uploadTemplate', async(() => {
  ...
  spyOn(component, 'uploadTemplate').and.callThrough();

  uploadTNativeElement.dispatchEvent(newEvent('click'));
  fixture.detectChanges();
  fixture.whenStable().then(() => {      
    expect(component.uploadTemplate).toHaveBeenCalled();
  });
}));