2

I have a TitleComponent that uses ActivedRoute.snapshot.data and Router to update data from app-routing.

This is my app-routing.module

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

  {
    path: 'home',
    component: MainHomeComponent,
    data: {
      title: 'Home',
    }
  },


];

@NgModule({
  imports: [RouterModule.forRoot(routes, {
    scrollPositionRestoration: 'enabled',
    anchorScrolling: 'enabled',
    scrollOffset: [0, 64] // [x, y]
  } )],
  exports: [RouterModule]
})
export class AppRoutingModule { }

and this is my TitleComponent.ts

export class TitleComponent implements OnInit {
  titleTab: string;
  subTitle: string;
  isTablet$: Subscribable<boolean> = this.breakpointsService.isTablet$;
  constructor(private router: Router, private route: ActivatedRoute, private breakpointsService: BreakpointsService) {
    this.router.events.subscribe((data) => {
      if (data instanceof NavigationEnd) {
        console.log('title is= ',this.route.snapshot.data['title']);
        // console.log(this.route.root.firstChild.snapshot.data.subTitle);
        this.titleTab = this.route.snapshot.data['title'];
        if (this.route.snapshot.data['subTitle']) {
          this.subTitle = this.route.snapshot.data['subTitle'];
        } else {
          this.subTitle = '';
        }
      }
    });
  }

  ngOnInit() {

  }

}

Now i want to test my TitleComponent. For example, when i navigate to home, i want to have titleTab === Home or Actived.snapshot.data['title'] = Home

How do it? I tried many ways buti always have errors.

My spec.ts

 fdescribe('TitleComponent', () => {
      let component: TitleComponent;
      let fixture: ComponentFixture<TitleComponent>;
      let location: Location;
      let router: Router;
      // let route: ActivatedRoute;
      const mockActivedRoute = jasmine.createSpyObj('ActivatedRoute', ['get']);
      const testRouter = jasmine.createSpyObj('Router', ['get'])
      const route = ({ data: of({ title: 'home' }) } as any) as ActivatedRoute;


      beforeEach(async(() => {
        TestBed.configureTestingModule({
          declarations: [
            TitleComponent,
            HomeComponent,
            SearchComponent,
            AppComponent,
            MainHomeComponent,
          ],
          providers: [
            {
              provide: ActivatedRoute,
              useValue: {
                snapshot: {
                  data: { title: 'home' }
                }
              },
            }
          ],
          imports: [RouterTestingModule.withRoutes(routes)],
          schemas: [NO_ERRORS_SCHEMA],
        }).compileComponents();

        router = TestBed.get(Router);
        location = TestBed.get(Location);
        router.initialNavigation();
      }));

      beforeEach(() => {
        fixture = TestBed.createComponent(TitleComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
      });



      // It doesn't works with mock

      it('test home data', fakeAsync(() => {
        router.navigate(['/home']);
        tick();
        expect(route.snapshot.data.title).toBe('title');


         }));

    // It doesn't works with component
     //it('test ', fakeAsync(() => {
        //router.navigate(['/home']);
        //tick();
        //expect(component.titleTab).toBe('home');
   // }));

Help me please.

user9714967
  • 1,534
  • 3
  • 13
  • 21

1 Answers1

0

Router navigation is asynchronous, so my guess is that you should wait for router event to complete. Here is what I would use:

it('should....', (done) => {
 router.navigate(['/home'])
            .then(() => {
                fixture.detectChanges();

                expect(....);
                done();
            })
            .catch(err => fail(err));
    });