我的目标是对NewServicesRequestsComponent进行单元测试,我能够解析其他依赖关系,但仍停留在名为GenericService的服务依赖关系
我尝试通过在规范文件中将其作为提供程序并使用Mockbackend作为提供程序来解决XHRbackend错误,一旦XHRbackend被解决,则给出了“没有为RequestOptions提供程序”错误,因此在搜索上述错误时遇到了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提供程序
预期: 至少要对组件进行单元测试
答案 0 :(得分:4)
好的,我会为此开枪。试图为这个问题想出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
的真实方法提供一个良好的开端。
编码愉快。 :)