如何使Angular5 spyOn正常工作?

时间:2018-09-04 17:44:52

标签: angular angular5 bluebird stub spy

我的测试未检测到更改。这是我的组件:

import com.android.build.OutputFile

我的测试有:

  toggleUploadModal() {
    const modalRef = this.ngbModal.open(UploadFilesComponent, { size: 'lg', backdrop: 'static' });
    modalRef.componentInstance.DeliverableTransaction = this.transactionDetails;
    modalRef.result.then((res) => {
      if (res.status === 'success') {
        this.deliverableTransactionService.updateDeliverableTransaction(this.route.snapshot.params.id, {
          submissionStatus: 'In Process'
        })
      }
      setTimeout(() => {
        this.uploadStatus = {};
      }, 5000);
    })
  }

但是, beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [TransactionFileViewer, NgxPermissionsAllowStubDirective], providers: [...], imports: [...], schemas: [ NO_ERRORS_SCHEMA, CUSTOM_ELEMENTS_SCHEMA ], }) .compileComponents(); fixture = TestBed.createComponent(TransactionFileViewer); downloadService = TestBed.get(DownloadService); component = fixture.componentInstance; fixture.detectChanges(); submissionFileService = TestBed.get(SubmissionFileService); deliverableDefinitionService = TestBed.get(DeliverableDefinitionService); service = TestBed.get(DeliverableDefinitionDetailViewService); deliverableTransactionService = TestBed.get(DeliverableTransactionService); modalService = TestBed.get(NgbModal); flashMessagesService = TestBed.get(FlashMessagesService); })); fit('should update the submissionStatus upon file upload', () => { spyOn(modalService, 'open').and.returnValue({ componentInstance: {}, result: Promise.resolve({ uploadedFileCount: 5, status: 'success' }) }); spyOn(deliverableTransactionService, 'updateDeliverableTransaction').and.returnValue(true); component.toggleUploadModal(); expect(deliverableTransactionService.updateDeliverableTransaction).toHaveBeenCalledWith(1, { submissionStatus: 'In Process' }); }) 从未在测试中被调用。我究竟做错了什么?我认为我需要以某种方式将范围绑定到updateDeliverableTransaction,但不确定如何。如果有问题,我正在使用result

1 个答案:

答案 0 :(得分:2)

updateDeliverableTransaction方法将不会调用,因为它处于模​​式的成功回调中。您需要在方法调用后添加fixture.detectChanges()

尝试一下

fit('should update the submissionStatus upon file upload', () => {
    spyOn(modalService, 'open').and.returnValue({
      componentInstance: {},
      result: Promise.resolve({
        uploadedFileCount: 5,
        status: 'success'
      })
    });
    spyOn(deliverableTransactionService, 'updateDeliverableTransaction').and.returnValue(true);

    component.toggleUploadModal();
    fixture.detectChanges();
    expect(deliverableTransactionService.updateDeliverableTransaction).toHaveBeenCalledWith(1, {
      submissionStatus: 'In Process'
    });
  })