我想測驗一個使用路由器導航到另一個頁面的方法,該方法的名稱是goToView():
goToView(): void {
this.router.navigate(['../' this.view],{relativeTo:this.activeRoute})
}
在我的規范類中,我添加了這個:
describe('HomeRedirectionBoxComponent', () => {
let component: HomeRedirectionBoxComponent;
let fixture: ComponentFixture<HomeRedirectionBoxComponent>;
let location: Location;
let router: Router;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [HomeRedirectionBoxComponent],
imports: [RouterTestingModule.withRoutes(appRoutes)],
}).compileComponents();
fixture = TestBed.createComponent(HomeRedirectionBoxComponent);
component = fixture.componentInstance;
router = TestBed.get(Router);
location = TestBed.get(Location);
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should navigate to dashboard', fakeAsync( () => {
const navigateSpy = spyOn(router, 'navigate');
component.goToView();
expect(navigateSpy).toHaveBeenCalledWith(['/dashboard']);
}));
});
失敗的方法:
it('should navigate to dashboard', fakeAsync( () => {
const navigateSpy = spyOn(router, 'navigate');
component.goToView();
expect(navigateSpy).toHaveBeenCalledWith(['/dashboard']);
}));
錯誤資訊:

問題是,當我第一次加載我的應用程式時,我重定向到“/homePage”,在我的 AppRouteModule 下方配置路由和重定向:
const appRoutes: Routes = [
{ path: '', redirectTo: '/homePage', pathMatch: 'full' },
{ path: 'homePage', component: HomePageComponent },
{ path: 'dashboard', component: DashboardComponent },
];
@NgModule({
imports: [RouterModule.forRoot(appRoutes)],
exports: [RouterModule],
})
export class AppRoutingModule {}
export default appRoutes;
僅單擊 goToView() 方法時,如何設定特定的間諜?
uj5u.com熱心網友回復:
試試這個(按照評論!!):
describe('HomeRedirectionBoxComponent', () => {
let component: HomeRedirectionBoxComponent;
let fixture: ComponentFixture<HomeRedirectionBoxComponent>;
let location: Location;
let router: Router;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [HomeRedirectionBoxComponent],
//!! remove withRoutes, it is not necessary for the test to know about your routes
imports: [RouterTestingModule],
}).compileComponents();
fixture = TestBed.createComponent(HomeRedirectionBoxComponent);
component = fixture.componentInstance;
router = TestBed.get(Router);
location = TestBed.get(Location);
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should navigate to dashboard', fakeAsync( () => {
const navigateSpy = spyOn(router, 'navigate');
component.goToView();
//!! get the first argument
const firstArg = navigateSpy.calls.mostRecent().args[0];
//!! expect ['../dashboard'] to contain 'dashboard'
expect(firstArg[0]).toContain('dashboard');
}));
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/372014.html
