Тестовое покрытие не покрывает вызов функции - PullRequest
0 голосов
/ 12 февраля 2020

Я написал тест в Angular 8, чтобы проверить, вызывается ли диалог подтверждения, и он работает абсолютно нормально. Мой тестовый охват не проходит, говоря, что

() => this.confirm () в приведенном ниже утверждении не охватывается тестом. Может кто-нибудь сказать мне, что мне не хватает?

 this.confirmationDialog.show(this.confirmMessage, 'Sodan Email', () => this.confirm());

Основной компонент

constructor(
    private router: Router,
    private route: ActivatedRoute,
    private service: SubmissionsService,
    private messageService: MessageService,
    private approvalsService: ApprovalsService,
    public confirmationDialog: ConfirmationDialogService,
   public userService: UserService) {
    this.service
      .getStatuses()
      .then((result: any[]) => this.statuses = result);

    this.route.params.subscribe(params => {
      this.service.get(params['quoteId'], params['quote']).then(x => {
        this.sale = x;
        this.saving = false;

        this.approvalsService
          .getStatusesForClientId(this.sale.vendorProductQuote.clientId)
          .then(result => this.approvals = result);

        if (this.sale.id) {
          this.service
            .getComments(this.sale.id)
            .then((result: any[]) => this.comments = result);
        }
      });
    });
  }

  public save() {
    this.service.save(this.sale).then(() => {
      this.messageService.add('Successfully saved.', 'success');
      this.navigateToSubmissionsList();
    }).finally(() => {
      this.saving = false;
    });
    return false;
  }

  public sendEmail = () =>  {
    this.confirmationDialog.show(this.confirmMessage, 'Sodan Email', () => this.confirm());
  }

  public confirm = () => this.service.sendEmail(this.sale.vendorProductQuote.clientId);

  public saveComment() {
    this.service.saveComment(<any>{ id: this.sale.id, vendorProductSaleComment: this.comment }).then(() => {
      this.messageService.add('Comment saved.', 'success');
      this.comments.unshift({...this.comment, createdBy: this.userService.getCurrentUser().id, created: new Date()});
      this.comment = {};
    }).finally(() => {
      this.saving = false;
    });
    return false;
  }

  public navigateToSubmissionsList = () => this.router.navigate(['/submissions']);

  public addDefaultValidationMessages = item => AddDefaultValidationMessages(item);
}

Тест

describe('EditComponent', () => {
  let component: EditComponent;
  let fixture: ComponentFixture<EditComponent>;

  let mockSubmissionsService;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ EditComponent, FullPageLayoutComponent, SpinnerComponent ],
      imports: [
        DevExpressModule,
        SharedFontAwesomeModule,
        NgxPermissionsModule.forRoot(),
        RouterTestingModule.withRoutes([{ path: 'submissions', component: EditComponent }])
      ],
      providers: [
        { provide: SubmissionsService, useFactory: () => mockSubmissionsService.Object },
        {
          provide: ApprovalsService,
          useValue: new Mock<ApprovalsService>({ getStatusesForClientId: () => Promise.resolve([]) }).Object
        },
        {
          provide: UserService,
          useValue: new Mock<UserService>({ getCurrentUser: () => <IUser>{} }).Object
        },
        { provide: MessageService, useClass: MockMessageService },
        {
          provide: ConfirmationDialogService,
          useValue:  new Mock<ConfirmationDialogService>({ show: () => Promise.resolve(mockSubmissionsService.sendEmail)  }).Object
        },
      ]

    })
      .compileComponents();
  }));

  beforeEach(() => {
    mockSubmissionsService = new Mock<SubmissionsService>({
      get: () => Promise.resolve({ vendorProductQuote: {}, id: 1 }),
      getStatuses: () => Promise.resolve([]),
      getComments: () => Promise.resolve([]),
      sendEmail: () => Promise.resolve({}),
      save: () => Promise.resolve({}),
      saveComment: () => Promise.resolve({})
    });
  });

  it('should create', () => {
    mockSubmissionsService.extend({ get: () => Promise.resolve({ vendorProductQuote: {} }) });

    fixture = TestBed.createComponent(EditComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

    expect(component).toBeTruthy();
  });

  it('should call service when save is called', () => {
    mockSubmissionsService.extend({ get: () => Promise.resolve({ vendorProductQuote: {}, id: 1 }) });

    fixture = TestBed.createComponent(EditComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

    fixture.ngZone.run(() => component.save());
    expect((<any>component).service.save).toHaveBeenCalled();
  });

  it('should call confirmationDialog when sendemail is called', () => {
    const vendorProductSale = { vendorProductQuote: { clientId: 198128 }, id: 1 };
    mockSubmissionsService.extend({ get: () => Promise.resolve(vendorProductSale) });

    fixture = TestBed.createComponent(EditComponent);
    component = fixture.componentInstance;
    component.sale = vendorProductSale;
    fixture.detectChanges();

    fixture.ngZone.run(() => component.sendEmail());
    expect((<any>component).confirmationDialog.show).toHaveBeenCalled();
  });

  it('should call service when confirm is called', () => {
    const vendorProductSale = { vendorProductQuote: { clientId: 198128 }, id: 1 };
    mockSubmissionsService.extend({ get: () => Promise.resolve(vendorProductSale) });

    fixture = TestBed.createComponent(EditComponent);
    component = fixture.componentInstance;
    component.sale = vendorProductSale;
    fixture.detectChanges();

    fixture.ngZone.run(() => component.confirm());
    expect((<any>component).service.sendEmail).toHaveBeenCalled();
  });


});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...