4

My aim is to unit test NewServicesRequestsComponent , I was able to resolve other dependencies but stuck with the service dependency named GenericService

I tried out resolving XHRbackend error by giving it as a provider in my spec file and using Mockbackend, once XHRbackend was resolved then it had given "No provider for RequestOptions" error, so while searching for the above error I came across that MockBackend has been deprecated and also @angular/http/testing was deprecated as well ,even after following through https://angular.io/guide/testing#component-with-a-dependency I am unable to resolve the issues pertaining to GenericServices. I have given component , spec and GenericService file below

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

  });

Actual results I am getting Error : No provider for RequestOptions Error : No provider for XHRBackend

Expected: Atleast the component should be unit tested

Enthu
  • 512
  • 2
  • 13
  • 38
  • 1
    Don't forget to accept the below answer, Enthu, if it helped you. While it is not mandatory, it is encouraged. – halfer Aug 04 '19 at 14:46

1 Answers1

4

It was quite hard trying to come up with a MCVE for this question! I eliminated most of the extraneous imports both at the file level and in your TestBed, trying to focus on what you said your problem is:

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

So concentrating on GenericService then, I put together this StackBlitz, which still has all the providers that you gave in new-services-request-component. If you had provided the html template as well I could have loaded some of the imports as well and seen how it would render, but again - I am trying to focus on the issue of GenericService. :)

As you can see I mocked all the service calls with spyObjects. In particular note:

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

And then in the TestBed I provided the following:

{ provide: GenericService, useValue: genericSpy },

All this is so that the service can now be mocked, and test values returned to test the methods inside NewServicesRequestComponent. For example, I made up a method in the component in the StackBlitz called fetchData(), which fetches a territory from the backend using the GenericService, and tested it. To test this I first set a mock returning the value I wanted from the service, then tested to see if the component saved that value to the class property as fetchData() was supposed to.

I hope this will give you a good start on mocking the real methods of your NewServicesRequestComponent.

halfer
  • 19,824
  • 17
  • 99
  • 186
dmcgrandle
  • 5,934
  • 1
  • 19
  • 38
  • Hi @dmcgrandle , sorry didn't ge a chance to apply this , I'll surely check and accept the answer , could you please help me with this one https://stackoverflow.com/questions/54232501/angular-4-adding-an-image-before-each-new-line-using-renderer – Enthu Jan 28 '19 at 14:12