【问题标题】:Need to resolve the service dependency error with the component using karma jasmine需要使用 karma jasmine 解决组件的服务依赖错误
【发布时间】:2019-06-05 05:12:27
【问题描述】:

我的目标是对 NewServicesRequestsComponent 进行单元测试,我能够解决其他依赖项,但坚持使用名为 GenericService 的服务依赖项

我尝试通过在我的规范文件中将其作为提供程序并使用 Mockbackend 来解决 XHRbackend 错误,一旦 XHRbackend 得到解决,它就会给出“No provider for RequestOptions”错误,因此在搜索上述错误时我遇到了MockBackend 已被弃用,@angular/http/testing 也已被弃用,即使在遵循 https://angular.io/guide/testing#component-with-a-dependency 我无法解决与 GenericServices 有关的问题。 我在下面给出了组件、规范和 GenericService 文件

新服务请求组件

 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
  }

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

通用服务

` 
   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 的提供者

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

【问题讨论】:

  • 不要忘记接受下面的答案,恩图,如果它对你有帮助的话。虽然这不是强制性的,但我们鼓励这样做。

标签: angular unit-testing karma-jasmine karma-runner angular2-testing


【解决方案1】:

很难为这个问题想出一个MCVE!我在文件级别和您的 TestBed 中消除了大部分无关的导入,试图专注于您所说的问题:

我能够解决其他依赖项,但坚持使用名为 GenericService 的服务依赖项

然后集中精力于 GenericService,我将这个 StackBlitz 放在一起,它仍然包含您在 new-services-request-component 中提供的所有提供程序。如果您也提供了 html 模板,我也可以加载一些导入并查看它的呈现方式,但是我再次尝试关注GenericService 的问题。 :)

如您所见,我使用 spyObjects 模拟了所有服务调用。特别注意:

const genericSpy = jasmine.createSpyObj('GenericService', ['getTerritory', 'post', 'put']);

然后在 TestBed 中我提供了以下内容:

{ provide: GenericService, useValue: genericSpy },

所有这些都是为了现在可以模拟服务,并返回测试值来测试NewServicesRequestComponent 中的方法。例如,我在 StackBlitz 的组件中编写了一个名为 fetchData() 的方法,该方法使用 GenericService 从后端获取 territory,并对其进行了测试。为了测试这一点,我首先设置了一个模拟,从服务返回我想要的值,然后测试该组件是否将该值保存到类属性中,就像 fetchData() 应该那样。

我希望这能让您在模拟 NewServicesRequestComponent 的真实方法方面有个良好的开端。

【讨论】:

猜你喜欢
  • 2023-03-26
  • 2018-04-07
  • 2017-09-05
  • 1970-01-01
  • 1970-01-01
  • 2019-05-19
  • 2016-02-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多