Angular - fixture.debugElement.query (By.directive (IsRouteDirective) не может найти элемент хоста - PullRequest
0 голосов
/ 16 мая 2019

Я пишу тесты для директивы, но не могу заставить запрос для элемента хоста директивы работать с использованием By.directive(IsRouteDirective).Ведение журнала консоли hostElement всегда дает null.

В приведенном ниже коде LibRouteComponent и LibTestComponent являются просто фиктивными компонентами с пустым шаблоном.

Вот директива (короткая версия):

@Directive({
  selector: '[libIsRoute]'
})

export class IsRouteDirective implements OnInit { ... }

И вот тестовая установка для него:

describe('IsRouteDirective', () => {

  let directive: IsRouteDirective;
  let fixture: ComponentFixture<LibTestComponent>;
  let hostElement;

  beforeEach(() => {

    fixture = TestBed.configureTestingModule({
      imports: [
        LibTestModule,
        RouterTestingModule.withRoutes([
          {
            path: '',
            pathMatch: 'full',
            redirectTo: 'foo'
          },
          {
            path: 'foo',
            component: LibRouteComponent
          },
          {
            path: 'bar',
            component: LibRouteComponent
          }
        ])
      ],
      declarations: [IsRouteDirective]
    })
    .overrideComponent(LibTestComponent, {
      set: {
        template: `
          <router-outlet></router-outlet>
          <div [libIsRoute]="['foo']"></div>
        `
      }
    })
    .createComponent(LibTestComponent);

    fixture.detectChanges();

    hostElement = fixture.debugElement.query(By.directive(IsRouteDirective));
    console.log(hostElement);
    directive = hostElement.injector.get(IsRouteDirective);

  });

  it('should be defined', () => {
    expect(hostElement).toBeTruthy();
  });
});

Использование By.css('div') дает DebugElement{nativeNode: <div libisroute=""></div>.... в журнале, который показывает, что элемент существует, и селектор директивыустановить на это.

Я делаю именно то, что делают официальные документы здесь .

Почему By.directive(IsRouteDirective) не работает в моем случае?

...