Angular 角度单元测试:TypeError:无法读取属性';根';未定义的
我正在Angular应用程序下进行单元测试 我的Angular版本是4.0.0 我的组件如下所示:Angular 角度单元测试:TypeError:无法读取属性';根';未定义的,angular,unit-testing,typescript,jasmine,testbed,Angular,Unit Testing,Typescript,Jasmine,Testbed,我正在Angular应用程序下进行单元测试 我的Angular版本是4.0.0 我的组件如下所示: component.ts: import { GdfaClientService } from '../../../service/gdfa-client.service'; import { SharedclientService } from '../../../service/sharedclient.service'; import { Client } from '../../model
component.ts
:
import { GdfaClientService } from '../../../service/gdfa-client.service';
import { SharedclientService } from '../../../service/sharedclient.service';
import { Client } from '../../model/client';
import { RouteNavigator } from '../../util/route-navigator';
import { Component, OnInit } from '@angular/core';
import {MonitoringService} from '../../../service/monitoring.service';
@Component({
selector: 'app-queue-again',
templateUrl: './queue-again.component.html',
styleUrls: ['./queue-again.component.css'],
})
export class QueueAgainComponent implements OnInit {
//-- variables --//
showError = false;
queueChoices = [];
selectedQueue;
selectedReason;
requestInProgress = false;
client: Client;
errorMessage: string;
queues: any;
bankNotAllowed: boolean = false;
constructor(private sharedclientService: SharedclientService, private gdfaClientService: GdfaClientService
, private router: RouteNavigator, private monitoringService: MonitoringService) { }
ngOnInit() {
this.client = this.sharedclientService.getShared360Client();
this.getQueues();
this.bankNotAllowed = this.sharedclientService.bankNotAllowed;
}
goToPrevious() {
this.router.goToHomeAccordingToProfile();
}
queueAgain() {
let currentNd = "";
let currentUniverse = "";
let currentCuid = "";
if (!this.selectedReason) {
return;
}
this.requestInProgress = true;
let reg = {
registrationId: this.client.registration.gdfaId,
gdfaQueueId: this.selectedQueue.id,
gdfaReasonId: this.selectedReason.id,
firstProfile: (this.client.firstProfile ? true : false)
};
this.gdfaClientService.queueAgain(reg).then(any => {
currentCuid = this.client.clientIdentity.customerId;
if (this.client.fromAdvSearch == undefined || this.client.fromAdvSearch == false) {
currentNd = this.client.nd;
if (currentNd != undefined && currentNd != "") {
if (currentNd == "0000000000") {
currentNd = "";
currentUniverse = "";
}
if (currentNd.substring(0, 2) == "06" || currentNd.substring(0, 2) == "07") {
currentUniverse = "Mobile";
} else {
currentUniverse = "Fixe";
}
}
}
this.trackReinsertClient(currentCuid, currentNd, currentUniverse);
this.requestInProgress = false;
this.showError = false;
this.sharedclientService.setShared360Client(new Client());
this.goToPrevious();
})
.catch(error => {
this.requestInProgress = false;
this.showError = true;
switch (error.status) {
case 403:
this.errorMessage = "Erreur lors de la réinjection du client : utilisateur inconnu";
console.log(this.errorMessage);
break;
case 500:
this.errorMessage = "Réinscription impossible";
console.log(this.errorMessage);
break;
default:
this.errorMessage = "Erreur lors de la réinjection du client";
console.log(this.errorMessage);
}
});
};
trackReinsertClient(cuid, nd, universe) {
let uri = "/api/gdfa/client/registration/reinsert";
let httpMethod = "PUT";
let name = "réinjection d'un client dans la file d'attente";
console.log('trackReinsertClient <' + cuid + '>');
this.monitoringService.trackingAction(name, uri, httpMethod, null, cuid, nd, universe);
}
selectQueue(queue) {
this.selectedQueue = queue;
this.selectedReason = false;
};
isSelectedQueue(queue) {
return this.selectedQueue.shortName == queue.shortName;
}
getQueues() {
let queueList = this.client.registration.queueAgainChoices;
// Search for residentiel queue and put it as selectedQueue
let indexSAVSAUMobile = -1;
let indexSAVSAUInternet = -1;
for (let queue of queueList) {
if (queue.shortName == 'RES')
this.selectedQueue = queue;
}
this.queues = queueList;
return queueList;
}
selectReason(reason) {
this.selectedReason = reason;
}
isSelectedReason(reason) {
if (this.selectedReason) {
return this.selectedReason.id == reason.id;
}
return null
}
getReasons(queue) {
let reasonList = this.selectedQueue.reasons;
return reasonList;
}
}
如您所见,我没有使用routeLink
在我的测试文件配置中,我完成了以下操作:
组件规范ts
:
import {async, ComponentFixture, TestBed, tick, fakeAsync} from '@angular/core/testing';
import {QueueAgainComponent} from './queue-again.component';
import {OrderByPipe} from 'app/home/pipe/order-by.pipe';
import {SharedclientService} from 'app/service/sharedclient.service';
import {GdfaClientService} from 'app/service/gdfa-client.service';
import {AuthHttp, AuthConfig, AUTH_PROVIDERS, provideAuth} from 'angular2-jwt';
import {HttpModule} from '@angular/http';
import {EnvVarsService} from 'app/service/env-vars.service';
import {RouteNavigator} from 'app/home/util/route-navigator';
import {Router} from '@angular/router';
import {Observable} from 'rxjs/Observable';
import * as QueueAgainMocks from 'TU/mocks/queue-again-mocks';
import {RouterTestingModule} from '@angular/router/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';
describe('QueueAgainComponent', () => {
let comp: QueueAgainComponent;
let fixture: ComponentFixture<QueueAgainComponent>;
let sharedclientService: SharedclientService;
let gdfaClientService: GdfaClientService;
let getShared360Client: jasmine.Spy;
let queueAgain: jasmine.Spy;
let client = QueueAgainMocks.CUSTOMER_MOCK;
let selectedQueue = QueueAgainMocks.SELECTED_QUEUE_MOCK;
let selectedReason = QueueAgainMocks.SELECTED_REASON;
let mockRouter = {
navigate: jasmine.createSpy('navigate')
};
// TestBed preparation (async)
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HttpModule , RouterTestingModule],
declarations: [QueueAgainComponent, OrderByPipe],
providers: [SharedclientService, GdfaClientService, AuthHttp, EnvVarsService, RouteNavigator,
{provide: Router, useValue: mockRouter},
provideAuth({
headerName: 'Authorization',
headerPrefix: 'bearer',
tokenName: 'token',
tokenGetter: (() => localStorage.getItem('id_token')),
globalHeaders: [{'Content-Type': 'application/json'}],
noJwtError: true
})
],
schemas: [ NO_ERRORS_SCHEMA ]
}).compileComponents();
}));
// Fixture & Spies declarations
beforeEach(() => {
// Creation of the component fixture
fixture = TestBed.createComponent(QueueAgainComponent);
comp = fixture.componentInstance;
fixture.detectChanges(); // this line will call components ngOnInit() method
// Getting Services instances from fixture
sharedclientService = fixture.debugElement.injector.get(SharedclientService);
gdfaClientService = fixture.debugElement.injector.get(GdfaClientService);
// Call of fake methods of `sharedclientService` from the AlertServiceSpy
getShared360Client = spyOn(sharedclientService, 'getShared360Client').and.returnValue(client);
// Call of fake methods of `gdfaClientService` from the AlertServiceSpy
queueAgain = spyOn(gdfaClientService, 'queueAgain').and.callFake((reg) => {
return Observable.of('ok');
});
comp.ngOnInit();
});
// Test case of component compilation
it('should be defined', () => {
expect(comp).toBeDefined();
});
});
从日志的最后一行指向53:27的那一行,正好是:
fixture = TestBed.createComponent(QueueAgainComponent);
因此,它似乎无法创建夹具
有什么想法吗?我也有同样的问题,只是解决了。 删除该行:
{provide: Router, useValue: mockRouter}
它会起作用的
问题是,当您导入RouterTestingModule
时,您应该删除所有路由器模拟提供程序,除了ActiveRoute
等
fixture = TestBed.createComponent(QueueAgainComponent);
{provide: Router, useValue: mockRouter}