I want to test a method that use a router to navigate to another page, the method's name is goToView():
goToView(): void {
this.router.navigate(['../' this.view],{relativeTo:this.activeRoute})
}
In my spec class I added this:
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']);
}));
});
The method which fails:
it('should navigate to dashboard', fakeAsync( () => {
const navigateSpy = spyOn(router, 'navigate');
component.goToView();
expect(navigateSpy).toHaveBeenCalledWith(['/dashboard']);
}));
The problem is that when I load my application first time, I have a redirection to "/homePage", bellow my AppRouteModule where I configure routes and redirections:
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;
How can I set specific spy when only I click the goToView() method?
CodePudding user response:
Try this (follow comments with !!):
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');
}));
});