Как протестировать угловой 7 компонент с ActiveRoute.snapshot.data и Router? - PullRequest
0 голосов
/ 21 февраля 2019

У меня есть TitleComponent, который использует ActivedRoute.snapshot.data и Router для обновления данных с app-routing.

Это мой 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 { }

, и этомой 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() {

  }

}

Теперь я хочу проверить свой TitleComponent.Например, когда я перехожу к дому, я хочу иметь titleTab === Home or Actived.snapshot.data['title'] = Home

Как это сделать?Я пробовал много способов, но всегда есть ошибки.

Мои спецификации.

 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');
   // }));

Помогите мне, пожалуйста.

1 Ответ

0 голосов
/ 30 июля 2019

Навигация по маршрутизатору асинхронна, поэтому я предполагаю, что вам следует дождаться завершения события маршрутизатора.Вот что я бы использовал:

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

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

...