【发布时间】:2017-11-07 13:02:46
【问题描述】:
在 Angular 4.0.0 下进行单元测试
我的测试用例如下:
test.spec.ts:
// Test Suite of Que-Again features
describe('QueueAgainComponent features', () => {
it('should navigate', () => {
comp.goToPrevious(); // HERE IS THE PROBLEM
expect(mockRouter.navigate).toHaveBeenCalledWith(['/home/pilote'], {skipLocationChange: true});
sharedclientService.user.isAdviser = true;
comp.goToPrevious();
expect(mockRouter.navigate).toHaveBeenCalledWith(['/home/advisor'], {skipLocationChange: true});
});
在配置部分我模拟了我的 RouteNavigator 服务,如下所示:
let mockRouter = {
navigate: jasmine.createSpy('navigate')
};
providers: [{provide: RouteNavigator, useValue: mockRouter}]
我的测试失败并抛出 tghis 错误:
TypeError: this.router.myMethod 不是函数
日志文件说问题点在 98:18 正是这一行:
comp.goToPrevious();
因此 goToPrevious() 在我的组件中实现如下:
goToPrevious() {
this.routeNavigator.myMethod();
}
而routeNavigator指的是一个自定义服务,用来处理自定义重定向,像这样:
**Route-navigator.service.ts**
import { LoginComponent } from '../../login/login.component';
import { SharedclientService } from '../../service/sharedclient.service';
import { Injectable } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
@Injectable()
export class RouteNavigator {
constructor(private router: Router, private sharedclientService: SharedclientService, private activatedRoute: ActivatedRoute) { }
accessAdvancedSearchFromRegistration = false;
accessSyntheseWhileGdfaShown = false;
track360View = false;
oldUrl: string;
private rdvReferer: string;
public navigateTo(url: string) {
this.oldUrl = this.router.url;
this.router.navigate([url], { skipLocationChange: true });
}
public myMethod() // HERE IS MY METHOD
{
if(this.sharedclientService.user != null && this.sharedclientService.user.isAdviser==null){
this.navigateTo('/home/blank');
this.sharedclientService.setCurrentRole('');
}
else if (this.sharedclientService.user != null && this.sharedclientService.user.isAdviser) {
this.navigateTo('/home/advisor');
this.sharedclientService.setCurrentRole('VENDEUR');
} else {
this.navigateTo('/home/pilote');
this.sharedclientService.setCurrentRole('PILOTE');
}
}
public goToNextAdvancedSearch() {
if (this.accessAdvancedSearchFromRegistration || !this.sharedclientService.user.isAdviser) {
this.navigateTo('/home/registration');
}
else {
this.track360View = true;
this.navigateTo('/home/view-360');
}
}
public exitAdvancedSearch() {
if (this.accessAdvancedSearchFromRegistration) {
this.navigateTo('/home/registration');
}
else {
this.goToHomeAccordingToProfile();
}
}
goToRdv(url?:string) {
if(!url)
this.rdvReferer = this.router.url;
else this.rdvReferer=url;
this.navigateTo('/home/appointment');
}
exitRdv() {
this.navigateTo(this.rdvReferer);
}
goToBlank() {
this.navigateTo('/home/blank');
}
public url() {
return this.router.url;
}
}
关于问题出在哪里或如何处理它的任何想法?
【问题讨论】:
标签: javascript angular unit-testing typescript jasmine