After creating an application with various components and successfully implementing navigation between pages, I am now looking to write tests for the routing section. Below is my router.spec.ts
:
import { Location } from "@angular/common";
import { TestBed, fakeAsync, tick, async } from "@angular/core/testing";
import { RouterTestingModule } from "@angular/router/testing";
import { Router } from "@angular/router";
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { AppComponent } from '../app.component';
describe('AppComponent', () => {
let location: Location;
let router: Router;
let fixture;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [HomeComponent, AboutComponent, AppComponent],
imports: [RouterTestingModule]
}).compileComponents();
router = TestBed.get(Router);
location = TestBed.get(Location);
fixture = TestBed.createComponent(AppComponent);
router.initialNavigation();
}));
it('should create the app', async(() => {
const fixture = TestBed.createComponent(AppComponent);
console.log(fixture);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));
it('navigate to "home" redirects you to /home', fakeAsync(() => {
router.navigate(['home']);
tick();
expect(location.path()).toBe('/home');
}));
// it('navigate to "about" takes you to /about', fakeAsync(() => {
// router.navigate(['about']);
// tick();
// expect(location.path()).toBe('/about');
// }));
});
Here is my splash-routing.module.ts:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { RootComponent } from './root/root.component';
import { AboutComponent } from './about/about.component';
import { PricingComponent } from './pricing/pricing.component';
import { ContactComponent } from './contact/contact.component';
import { LoginComponent } from './login/login.component';
import { HomeComponent } from './home/home.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
export const routes: Routes = [
{path: '', component: RootComponent, children: [
{path: '', component: HomeComponent},
{path: 'home', component: HomeComponent},
{path: 'about', component: AboutComponent},
{path: 'pricing', component: PricingComponent},
{path: 'contact', component: ContactComponent},
{path: 'login', component: LoginComponent},
{path: 'notfound', component: PageNotFoundComponent},
{
path: '**', // bonus: all routes not defined forward to /home
redirectTo: 'notfound'
},
{path: '', redirectTo: 'home'},
]},
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class SplashRoutingModule { }
While running tests using ng test
, I encountered an error as shown in this image: https://i.sstatic.net/msTlK.jpg. Can someone help me understand what I'm doing wrong? I also need to write tests for other components, so any guidance would be greatly appreciated.