测试正在从服务更改路由器



我有一个Angular应用程序版本8,我有一项服务可以像这样更改路由器:

@Injectable({
providedIn: 'root'
})
export class RoutingService implements OnDestroy {
constructor(
private router: Router) {}
public changeRoute(selectRoute1: string, selectRoute2: string): void {
this.router.navigate(['/' + selectRoute1 + '/' + selectRoute2]);
return;
}

服务正常工作。

我必须用Jasmine和Karma创建一个测试用例(但它不起作用(:

import { HttpClientTestingModule } from '@angular/common/http/testing';
import { async, fakeAsync, TestBed } from '@angular/core/testing';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { NgbDatepickerModule, NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { NgSelectModule } from '@ng-select/ng-select';
import { EffectsModule } from '@ngrx/effects';
import { Store, StoreModule } from '@ngrx/store';
describe('Routing Service', () => {
let routingService: RoutingService;
let router: Router;
let store: Store<any>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
ReactiveFormsModule,
RouterTestingModule,
NgbDatepickerModule,
NgbModule,
DfModule,
NgSelectModule,
NgOptionHighlightModule,
FormsModule,
StoreModule.forRoot({}),
StoreModule.forFeature('scope', scopeReducer),
EffectsModule.forRoot([]),
HttpClientTestingModule,
NgSelectModule
],
providers: [{
provide: Router,
useValue: {
routerState: {
snapshot : {
url :  '/h1/h2'
}
}
}
}
],
declarations: [AppComponent, FoxComponent],
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents();
}));
beforeEach(() => {
routingService = TestBed.get(RoutingService);
store = TestBed.get(Store);
});

it('should change the route', fakeAsync(() => {
const navigateSpy = spyOn(router);
routingService.changeRoute('fox', 'tango);
window.setTimeout(function waitAgainForCloseCallback() {
expect(navigateSpy).toHaveBeenCalledWith(['/fox/tango'])
}, 10);
}));
});

但它不起作用。为了修复它或编写另一个单元测试,你有什么想法吗?

您得到的错误是什么?

试试这个:

it('should change the route', fakeAsync(() => {
// add this line
router = TestBed.get(Router);
// change this line
const navigateSpy = spyOn(router, 'navigate');
routingService.changeRoute('fox', 'tango);
expect(navigateSpy).toHaveBeenCalledWith(['/fox/tango'])
}));

最新更新