1

Я пытаюсь проверить работу маршрутизации. Я переместил навигатор на отдельный компонент - MdNavbar. В основном только html и css там, RouteConfig находится в другом компоненте, и там вводится MdNavbar. Я хочу проверить изменения маршрута при нажатии на ссылку. В тесте я ищу ссылку профиля и нажимаю на нее. Я ожидаю, что маршрут изменится. Вот код из моих тестов -Тестирование директивы routerLink в Angular 2

import {it, inject,async, describe, beforeEachProviders, tick, fakeAsync} from '@angular/core/testing'; 

import {TestComponentBuilder} from '@angular/compiler/testing'; 
import {Component, provide} from '@angular/core'; 

import {RouteRegistry, Router, ROUTER_PRIMARY_COMPONENT, ROUTER_DIRECTIVES,RouteConfig} from '@angular/router-deprecated';  
import {Location, LocationStrategy, PathLocationStrategy} from '@angular/common'; 

import {RootRouter} from '@angular/router-deprecated/src/router'; 
import {SpyLocation} from '@angular/common/testing'; 

import {IndexComponent} from '../../home/dashboard/index/index.component'; 
import {ProfileComponent} from '../../home/dashboard/profile/profile.component'; 

// Load the implementations that should be tested 
import {MdNavbar} from './md-navbar.component';  

describe('md-navbar component',() => { 
    // provide our implementations or mocks to the dependency injector 
    beforeEachProviders(() => [ 
    RouteRegistry, 
    provide(Location, { useClass: SpyLocation }), 
    { provide: LocationStrategy, useClass: PathLocationStrategy }, 
    provide(Router, { useClass: RootRouter }), 
    provide(ROUTER_PRIMARY_COMPONENT, { useValue: TestComponent }), 
    ]); 

    // Create a test component to test directives 
    @Component({ 
    template: '', 
    directives: [ MdNavbar, ROUTER_DIRECTIVES ] 
    }) 
    @RouteConfig([ 
    { path: '/', name: 'Index', component: IndexComponent, useAsDefault: true }, 
    { path: '/profile', name: 'Profile', component: ProfileComponent }, 
    ]) 
    class TestComponent {} 

    it('should be able navigate to profile', 
     async(inject([TestComponentBuilder, Router, Location], 
     (tcb: TestComponentBuilder, router: Router, location: Location) => { 
     return tcb.overrideTemplate(TestComponent, '<md-navbar></md-navbar>') 
     .createAsync(TestComponent).then((fixture: any) => { 
      fixture.detectChanges(); 

      let links = fixture.nativeElement.querySelectorAll('a'); 
      links[8].click() 
      expect(location.path()).toBe('/profile'); 


     // router.navigateByUrl('/profile').then(() => { 
     //  expect(location.path()).toBe('/profile'); 
     // }) 
     }) 
    }))); 

Тест работает со следующим результатом -

Expected '' to be '/profile'. 

, а второй -

Может кто-то пожалуйста, дайте мне подсказку, что именно я» Неправильно?

Вот шаблон часть Navbar компонент -

<nav class="navigation mdl-navigation mdl-color--grey-830"> 
<a [routerLink]="['./Index']" class="mdl-navigation__link" href=""><i class="material-icons" role="presentation">home</i>Home</a> 
<a [routerLink]="['./Profile']" class="mdl-navigation__link" href=""><i class="material-icons" role="presentation">settings</i>My Profile</a> 
</nav> 

ДОБАВЛЕНО: Благодаря Гюнтер Zöchbauer ответ мне удалось найти рабочее решение для меня.

it('should be able navigate to profile', 
     async(inject([TestComponentBuilder, Router, Location], 
     (tcb: TestComponentBuilder, router: Router, location: Location) => { 
     return tcb.overrideTemplate(TestComponent, '<md-navbar></md-navbar>') 
     .createAsync(TestComponent).then((fixture: any) => { 
      fixture.detectChanges(); 

      let links = fixture.nativeElement.querySelectorAll('a'); 
      links[8].click(); 
      fixture.detectChanges(); 

      setTimeout(() { 
      expect(location.path()).toBe('/profile'); 
      }); 
     }) 
    }))); 

ответ

1

Событие click обрабатывается async. Вам нужно будет задержать проверку для измененного пути.

it('should be able navigate to profile', 
     inject([TestComponentBuilder, AsyncTestCompleter, Router, Location], 
     (tcb: TestComponentBuilder, async:AsyncTestCompleter, router: Router, location: Location) => { 
     return tcb.overrideTemplate(TestComponent, '<md-navbar></md-navbar>') 
     .createAsync(TestComponent).then((fixture: any) => { 
      fixture.detectChanges(); 

      let links = fixture.nativeElement.querySelectorAll('a'); 
      links[8].click() 
      setTimeout(() { 
      expect(location.path()).toBe('/profile'); 
      async.done(); 
      }); 


     // router.navigateByUrl('/profile').then(() => { 
     //  expect(location.path()).toBe('/profile'); 
     // }) 
     }) 
    }))); 

или

it('should be able navigate to profile', 
     async(inject([TestComponentBuilder, Router, Location], 
     (tcb: TestComponentBuilder, router: Router, location: Location) => { 
     return tcb.overrideTemplate(TestComponent, '<md-navbar></md-navbar>') 
     .createAsync(TestComponent).then((fixture: any) => { 
      fixture.detectChanges(); 

      let links = fixture.nativeElement.querySelectorAll('a'); 
      links[8].click() 
      return new Promise((resolve, reject) => { 
      expect(location.path()).toBe('/profile'); 
      resolve(); 
      }); 


     // router.navigateByUrl('/profile').then(() => { 
     //  expect(location.path()).toBe('/profile'); 
     // }) 
     }) 
    }))); 

Я не использую машинопись сам, поэтому синтаксис может быть выключен.

+0

Большое спасибо за помощь. Несмотря на то, что оба решения не помогли мне (довольно уверен, что из-за моего отсутствия понимания), но когда я немного изменил ваше первое решение, которое сделало трюк. – renchan

+1

Рад слышать, что вы можете заставить его работать. Как я уже сказал, я не использую TS самостоятельно, и в последнее время очень много меняется, как асинхронные тесты могут указывать, что они завершены. Я просто просмотрел несколько тестов в реверсе Angular GitHub, чтобы проверить, как они это делают. Основная идея заключается в том, что обработчик события click выполняет async - но вы все равно это получили. –

Смежные вопросы