Angular RouterLink маршруты неправильно в тесте - PullRequest
0 голосов
/ 05 апреля 2020

Я пытаюсь проверить щелчок маршрутизатора, который должен перенаправляться из / parent в / parent / child в root router-outlet. Когда я запускаю свое приложение , все работает , но в моем тесте я получаю следующее сообщение об ошибке:

Ошибка: невозможно сопоставить никакие маршруты. Сегмент URL: 'child'

Мои маршруты:

export const routes: Routes = [
  {
    path: 'parent',
    pathMatch: 'full',
    component: ParentComponent
  },

  {
    path: 'parent/child',
    component: ChildComponent
  }

];

HTML для родителя (/ parent), который должен направлять в / parent / child

<a routerLink="./child">child</a>

это работает также, но не в тесте:

<a routerLink="child">child</a>

Мой тест:

describe('ParentComponent', () => {
  let component: ParentComponent;
  let fixture: ComponentFixture<ParentComponent>;

  let location: Location;
  let router: Router;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule.withRoutes(routes),
        AppModule
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ParentComponent);
    component = fixture.componentInstance;
    router = TestBed.get(Router);
    location = TestBed.get(Location);
    fixture.detectChanges();
  });

  it('router to child test', fakeAsync(() => {
    router.navigate(["/parent"]);
    tick();
    expect(location.path()).toBe("/parent")
    fixture.debugElement.query(By.css("a")).nativeElement.click();
    tick();
    expect(location.path()).toBe("/parent/child");
  }));
});

Сам маршрут есть, потому что, когда я пытаюсь что-то подобное, он работает:

 it('router to child test', fakeAsync(() => {
    router.navigate(["/parent"]);
    tick();
    expect(location.path()).toBe("/parent")
    //fixture.debugElement.query(By.css("a")).nativeElement.click();
    router.navigate(["/parent/child"]);

    tick();
    expect(location.path()).toBe("/parent/child");
  }));

Похоже, мой тест не может напрямую работать с routerLink.

1 Ответ

1 голос
/ 05 апреля 2020

Похоже, вы пытаетесь проверить внутреннюю работу Angular.

Вместо этого достаточно было бы проверить, имеет ли элемент правильное значение атрибута в routerLink, и доверить инфраструктуру поступите правильно.

Примерно так:

  it('renders the correct routerLink attribute to the child component', () => {
    const anchor = fixture.debugElement.query(By.css('a'));

    expect(anchor.nativeElement.getAttribute('routerLink')).toEqual('./child');
  });

ОБНОВЛЕНИЕ

Да, во время модульного тестирования дочерний маршрут не добавляется в родительский маршрут.

router.navigate(['./child']); // <-- not working

теперь давайте go вернемся к вашей первоначальной реализации:

router.navigate(["/parent/child"]); // <-- it works

теперь, чтобы заставить его работать из ваш html вы можете изменить атрибут routerLink на это:

<a routerLink="/parent/child">child</a>

теперь ваш модульный тест пройдет.

  it('router to child test', fakeAsync(() => {
    router.navigate(['/parent']);
    tick();

    expect(location.path()).toBe('/parent');

    fixture.debugElement.query(By.css('a')).nativeElement.click();    
    tick();

    expect(location.path()).toBe('/parent/child');
  }));

Также обратите внимание на children атрибут в конфигурации маршрута для создания истинных дочерних маршрутов. Примерно так:

  {
    path: 'parent',
    component: ParentComponent,
    children: [
      {
        path: 'child',
        component: ChildComponent
      }
    ]
  },
...