加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – 需要使用karma jasmine解决组件的服务依赖性错误

发布时间:2020-12-17 17:37:24 所属栏目:安全 来源:网络整理
导读:我的目标是单元测试NewServicesRequestsComponent,我能够解决其他依赖项,但坚持使用名为GenericService的服务依赖项 我尝试解决XHRbackend错误,将其作为我的spec文件中的提供者并使用Mockbackend,一旦XHRbackend被解析,然后它给出了“No Provider forptionsO
我的目标是单元测试NewServicesRequestsComponent,我能够解决其他依赖项,但坚持使用名为GenericService的服务依赖项

我尝试解决XHRbackend错误,将其作为我的spec文件中的提供者并使用Mockbackend,一旦XHRbackend被解析,然后它给出了“No Provider forptionsOptions”错误,所以在搜索上述错误时我发现MockBackend已经不推荐使用,@ angular / http / testing也被弃用了,即使在完成后也是如此
https://angular.io/guide/testing#component-with-a-dependency
我无法解决与GenericServices有关的问题.
我在下面给出了component,spec和GenericService文件

NewServicesRequestComponent

import { Router,ActivatedRoute,NavigationEnd } from '@angular/router';
 import { FormGroup,NgForm } from '@angular/forms';
 import { Component,OnInit,Input,Output,EventEmitter,ViewChild,Inject 
 } from '@angular/core';

 import * as $from 'jquery';

 import { environment } from './../../../environments/environment';
 import { ModalComponent } from './../../shared/modal/modal.component';
 import { GenericService } from './../../core/services/generic.service';

 import { ServiceControllerService } from './../../service/api/service- 
 controller.service';
 import { ServiceType } from '../../service/types/service.type';
 import { NgDatepickerModule,DatepickerOptions } from 'ng2-datepicker';
 import { Territory } from '../../models/territory';
 import { GLOBALS,Global } from './../../core/globals/global';

 import { AddServicesComponent } from '../new-services-request/add- 
 services/add-services.component';
 import { ServiceRequestService } from './new-services- 
 request.component.service';
 import { NavbarService } from '../../core/services/navbar.service';
 import { HeaderbarService } from '../../core/services/headernav.service';
 import { Subject } from 'rxjs/Subject';
 import { WBSSearch } from '../../shared/integrations/wbs/wbsModel';
 import { LineOfService } from '../../models/line.of.service';
 import { BusinessUnit } from '../../models/business.unit';
 import { RequestPackage } from './request.package';
 import { ServiceRequestDataSharing } from '../service-request-data- 
 sharing';
 import { OrderByPipe } from './../../shared/shared-pipes/order-by.pipe';
 import { RestrictionFolderSearchModel } from 
 '../../restriction/restrictionFolderSearchModel';
 import { RibbonMessageComponent } from '../../shared/ribbon- 
 message/ribbon-message.component';
 import { RibbonMessageService } from '../../shared/ribbon-message/ribbon- 
 message.service';
 import { EngagementForecast } from './types/engagement-forecast.type';

 const loadingActions = {
 renderAssuranceFields: 'NEW-SERVICES-REQUEST-RENDER-ASSURANCE-FIELDS',getAllRestrictionConfigs: 'NEW-SERVICES-GET-ALL-RESTRICTION-CONFIGS',loadBusinessUnits: 'NEW-SERVICES-LOAD-BUSINESS-UNITS',fetchWBSfromIntegration: 'NEW-SERVICES-FETCH-WBS-FROM-INTEGRATION',checkEngagementDuplicacy: 'NEW-SERVICE-CHECK-ENGAGEMENT-DUPLICACY',saveDraftEngagement: 'NEW-SERVICE-SAVE-DRAFT-ENGAGEMENT',otherSaveDraftEngagement: 'NEW-SERVICE-OTHER-SAVE-DRAFT-ENGAGEMENT',updateExistingEngagement: 'NEW-SERVICE-UPDATE-EXISTING-ENGAGEMENT',deleteEngagement: 'NEW-SERVICE-DELETE-ENGAGEMENT',submitServiceEngagementPackage: 'NEW-SERVICE-SUBMIT-SERVICE-ENGAGEMENT- 
 PACKAGE',getUsersInEngDelRoles: 'NEW-SERVICE-GET-USERS-IN-ENG-DEL-ROLES'
 };

@Component({
selector: 'app-new-services-request',templateUrl: './new-services-request.component.html',styleUrls: ['./new-services-request.component.scss']
   })

   export class NewServicesRequestComponent implements OnInit {
  @ViewChild('servReqForm') servReqForm: NgForm;
  @ViewChild('actionModalCancel') actionModalCancel: ModalComponent;
  @ViewChild('cancelActionModal') cancelActionModal: ModalComponent;
  @ViewChild('actionModalClaim') actionModalClaim: ModalComponent;
  @ViewChild('editResourceGroup') editResourceGroup: ModalComponent;
  @ViewChild('wbsErrorMessageRibbon') wbsErrorMessageRibbon: 
  RibbonMessageComponent;
  @ViewChild('gemMSG') gemMSG: RibbonMessageComponent;
  territory: any;
  businessUnit: any;
    options: DatepickerOptions = {
  //  minDate: new Date(this.currentDate.setDate(this.currentDate.getDate() 
  - 
  1)),displayFormat: 'MM/DD/YYYY'
    };

  constructor(@Inject(GLOBALS) private g: Global,private gs: 
  GenericService,public nav: NavbarService,private orderByPipe: OrderByPipe,public header: HeaderbarService,private serviceConfigService: ServiceControllerService,private router: 
  Router,private ribbonMessageService: RibbonMessageService,private route: ActivatedRoute,private serviceControllerAPI: 
  ServiceControllerService,public dataService: ServiceRequestService,private servReqDataSharing: ServiceRequestDataSharing) {
  var datepickerPos = this.datepickerPos;

}

 handleWBSChange(val) {
console.log(val.BillPartnerName);
 }

 ngOnInit() {}
  //various http and normal methods of generic service file being used
  }

====================

GenericService

` 
   import { Injectable,Inject } from '@angular/core';
   import { Http,XHRBackend,ConnectionBackend,RequestOptions,Request,RequestOptionsArgs,Response,Headers,ResponseContentType } from 
   '@angular/http';
   import 'rxjs/add/operator/map';
   import { Observable } from 'rxjs/Rx';
   import { Subject } from 'rxjs/Subject';
   import 'rxjs/add/operator/map';
   import 'rxjs/add/operator/catch';
   import 'rxjs/add/operator/do';
   import 'rxjs/add/operator/finally';
   import { environment } from './../../../environments/environment';
   import "rxjs/add/operator/toPromise";
   import "rxjs/add/operator/switchMap";
   import 'rxjs/add/observable/throw';
   import { ToastsManager,Toast } from 'ng2-toastr';
   import { HttpClient,HttpErrorResponse,HttpHeaders,HttpParams } from 
   '@angular/common/http';
   import { IdamAuthenticationService } from '@pa-util/angular2-idam';
   import { v4 as uuid } from 'uuid';
   import { CookieService } from 'ngx-cookie-service';
   import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
   import { catchError,retry } from 'rxjs/operators';
   import { Router } from '@angular/router'
   import { GLOBALS,Global } from '../globals/global';
   import { EngagementSharedDataForForecast } from 
   '../../forecast/forecast.type';
    import {RibbonMessageService} from '../../shared/ribbon-message/ribbon- 
   message.service';

   export interface IRequestOptions {
     headers?: HttpHeaders;
     observe?: 'body';
     params?: HttpParams;
     reportProgress?: boolean;
     responseType?: 'json';
     withCredentials?: boolean;
     body?: any;
    }
   export class iDamRequestOptions implements IRequestOptions { }
    @Injectable()

     export class GenericService {
      //various get,post,put,delete and other methods being used by 
      NewServicesRequestComponent
   }

NewServicesRequest.component.spec.ts

`

  import { async,ComponentFixture,TestBed } from '@angular/core/testing';
  import { NewServicesRequestComponent } from './new-services- 
  request.component';
  import { FormsModule,ReactiveFormsModule } from '@angular/forms';
  import { WbsComponent } from 
   './../../shared/integrations/wbs/wbs.component';
  import { MaxCharCheckPipe } from './../../shared/shared-pipes/maxchar- 
  validator.pipe';
  import { NgDatepickerModule } from 'ng2-datepicker';
  import { HandleTeamMemberComponent } from './../../shared/handle-team- 
  member/handle-team-member.component';
  import { ModalComponent } from './../../shared/modal/modal.component';
  import { DynamicFormAddServiceComponent } from './../../shared/dynamic- 
  form-add-service/dynamic-form-add-service.component';
  import {OrderByPipe} from './../../shared/shared-pipes/order-by.pipe';
  import { MandatoryCheckPipe } from './../../shared/mandatory-check.pipe';
  import { StringToBoolPipe } from './../../pipes/string-to-boolean.pipe';
  import { PeoplePickerComponent } from 
  './../../shared/integrations/people-picker/people-picker.component';
  import { PopoverModule } from 'ng2-popover';
  import { NoWhitespaceDirective } from './../../shared/whitespace- 
  validator/whitespace.directive';
  import {NG_VALIDATORS } from '@angular/forms';
  import { GLOBALS,Global } from './../../core/globals/global';
  import { GenericService } from './../../core/services/generic.service';
   import { HttpClientModule } from '@angular/common/http';
  import { HttpClientTestingModule,HttpTestingController } from 
  '@angular/common/http/testing';
  //import { XHRBackend } from '@angular/http';
  //import { MockBackend,MockConnection } from '@angular/http/testing';


   const GLOBALS1 = [{provide:GLOBALS}]
   fdescribe("new service request form",() =>{

   let component: NewServicesRequestComponent;
   let fixture: ComponentFixture<NewServicesRequestComponent>;

    beforeEach(async() => {
    TestBed.configureTestingModule({
     declarations : 
      [NewServicesRequestComponent,WbsComponent,MaxCharCheckPipe,HandleTeamMemberComponent,ModalComponent,DynamicFormAddServiceComponent,OrderByPipe,StringToBoolPipe,PeoplePickerComponent,MandatoryCheckPipe,NoWhitespaceDirective],imports:[FormsModule,ReactiveFormsModule,NgDatepickerModule,PopoverModule,HttpClientTestingModule],providers: [{ provide: NG_VALIDATORS,useExisting: 
       NoWhitespaceDirective,multi: true },GLOBALS1,GenericService]
     }).compileComponents();

  });

    beforeEach(() => { 
    fixture = TestBed.createComponent(NewServicesRequestComponent);
    component = fixture.debugElement.componentInstance;
    fixture.detectChanges();
    })

   it("is new service request form compoenent defined",() =>{

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

  });

我得到的实际结果
错误:没有RequestOptions的提供者
错误:没有XHRBackend的提供程序

预期:
至少应该对组件进行单元测试

解决方法

好的,我会拍这个.试图为这个问题提出一个 MCVE很难!我在文件级和TestBed中消除了大部分无关的导入,试图关注你所说的问题:

“I was able to resolve other dependencies but stuck with the service dependency named GenericService”

因此,专注于GenericService,我把这个StackBlitz放在一起,它仍然包含你在new-services-request-component中提供的所有提供者.如果您已经提供了html模板,我也可以加载一些导入并看看它将如何渲染,但是再次 – 我正在尝试关注GenericService的问题.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读