1

I made a simple app which is running correctly.

Now I am trying to write test cases of that application, so I tried with routing.

stackblitz

My routing code is this

Main module:

export const routes: Routes = [
  { path: '',   redirectTo: '/users', pathMatch: 'full' },

];
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    UserModule,
    HttpClientModule,
    RouterModule.forRoot(routes)

  ],

Feature module:

const routes: Routes = [
  {path: 'users', component: ListingComponent}

];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(routes)
  ],
  declarations: [ListingComponent]
})

Code

I try to run my spec but I am getting above error

describe('Initial navigation', () => {
    it('default route redirects to home (async)', fakeAsync(() => {
      router.initialNavigation(); // triggers default
      fixture.detectChanges();
      tick();
      console.log('==================');
      console.log(location.path());
      // fixture.whenStable().then(() => {
      expect(location.path()).toBe('/users');
      // })
    }));
  });
Community
  • 1
  • 1
user944513
  • 12,247
  • 49
  • 168
  • 318
  • Have you tried using `RouterTestingModule`? https://angular.io/api/router/testing/RouterTestingModule This post may help: https://stackoverflow.com/questions/39791773/angular-2-unit-testing-with-router – Narm Jun 05 '18 at 15:10
  • yes i used tis nodule – user944513 Jun 05 '18 at 16:11

1 Answers1

0

If you import UserModule to the spec, this resolves the error. As AppModule modules imports UserModule to register user feature/module routes, it must also be imported in the spec to ensure it's route registrations are available in the spec as well.

The need for this is implied at a basic level in the documentation Testing: Import a feature module.

//setup
beforeEach(() => {
  TestBed.configureTestingModule({
    imports: [
      UserModule, // import module
      RouterTestingModule.withRoutes(routes)],
    declarations: [
      TestComponent,
    ]
  });
  fixture = TestBed.createComponent(TestComponent);
  router = TestBed.get(Router);
  location = TestBed.get(Location);
});

Here is an updated StackBlitz demonstrating the functionality (test passing with no error).

Alexander Staroselsky
  • 37,209
  • 15
  • 79
  • 91