Подтвердить что ты не робот

Angular 2 единицы тестирования компонентов с помощью routerLink

Я пытаюсь проверить свой компонент с окончанием angular 2, но я получаю сообщение об ошибке, потому что компонент использует директиву routerLink. Я получаю следующую ошибку:

Невозможно связать с 'routerLink', так как это не известное свойство 'a'.

Это соответствующий код шаблона ListComponent

<a 
  *ngFor="let item of data.list" 
  class="box"
  routerLink="/settings/{{collectionName}}/edit/{{item._id}}">

И вот мой тест.

import { TestBed } from '@angular/core/testing';

import { ListComponent } from './list.component';
import { defaultData, collectionName } from '../../config';
import { initialState } from '../../reducers/reducer';


const data = {
  sort: initialState.sort,
  list: [defaultData, defaultData],
};

describe(`${collectionName} ListComponent`, () => {
  let fixture;
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        ListComponent,
      ],
    }).compileComponents(); // compile template and css;
    fixture = TestBed.createComponent(ListComponent);
    fixture.componentInstance.data = data;
    fixture.detectChanges();
  });

  it('should render 2 items in list', () => {
    const el = fixture.debugElement.nativeElement;
    expect(el.querySelectorAll('.box').length).toBe(3);
  });
});

Я просмотрел несколько ответов на подобные вопросы, но не смог найти решение, которое сработало для меня.

4b9b3361

Ответ 1

Вам нужно настроить всю маршрутизацию. Для тестирования вместо использования RouterModule вы можете использовать RouterTestingModule от @angular/router/testing, где вы можете настроить некоторые макетные маршруты. Вам также потребуется импортировать CommonModule из @angular/common для вашего *ngFor. Ниже приведен полный тест прохождения

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { By } from '@angular/platform-browser';
import { Location, CommonModule } from '@angular/common';
import { RouterTestingModule } from '@angular/router/testing';
import { TestBed, inject, async } from '@angular/core/testing';

@Component({
  template: `
    <a routerLink="/settings/{{collName}}/edit/{{item._id}}">link</a>
    <router-outlet></router-outlet>
  `
})
class TestComponent {
  collName = 'testing';
  item = {
    _id: 1
  };
}

@Component({
  template: ''
})
class DummyComponent {
}

describe('component: TestComponent', function () {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        CommonModule,
        RouterTestingModule.withRoutes([
         { path: 'settings/:collection/edit/:item', component: DummyComponent }
        ])
      ],
      declarations: [ TestComponent, DummyComponent ]
    });
  });

  it('should go to url',
    async(inject([Router, Location], (router: Router, location: Location) => {

    let fixture = TestBed.createComponent(TestComponent);
    fixture.detectChanges();

    fixture.debugElement.query(By.css('a')).nativeElement.click();
    fixture.whenStable().then(() => {
      expect(location.path()).toEqual('/settings/testing/edit/1');
      console.log('after expect');
    });
  })));
});

UPDATE

Другой вариант, если вы просто хотите проверить правильность отображения маршрутов, не пытаясь ориентироваться...

Вы просто импортируете RouterTestingModule без настройки каких-либо маршрутов

imports: [ RouterTestingModule ]

то просто проверьте, что ссылка отображается с правильным URL-адресом, например

let href = fixture.debugElement.query(By.css('a')).nativeElement
    .getAttribute('href');
expect(href).toEqual('/settings/testing/edit/1');

Ответ 2

Если вы не тестируете материал, связанный с маршрутизатором, вы можете настроить тест на игнорирование неизвестных директив с помощью "NO_ERRORS_SCHEMA"

 import { NO_ERRORS_SCHEMA } from '@angular/core';
 TestBed.configureTestingModule({
   declarations: [
     ListComponent,
   ],
   schemas: [ NO_ERRORS_SCHEMA ]
 });

Ответ 3

Записать тестовый пример для routerLink. Вы можете выполнить следующие шаги.

  • Импортировать RouterTestingModule и RouterLinkWithHref.

    import { RouterTestingModule } from '@angular/router/testing';
    import { RouterLinkWithHref } from '@angular/router';
    
  • Импорт RouterTestingModule в ваш модуль

    TestBed.configureTestingModule({
      imports: [ RouterTestingModule.withRoutes([])],
      declarations: [ TestingComponent ]
    })
    
  • В тестовом случае найдите директиву RouterLinkWithHref tot test для существования ссылки.

    it('should have a link to /', () => {
    const debugElements = fixture.debugElement.queryAll(By.directive(RouterLinkWithHref));
    const index = debugElements.findIndex(de => {
      return de.properties['href'] === '/';
    });
    expect(index).toBeGreaterThan(-1);
    

    });