Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - fixture.debugElement.query(By.directive(IsRouteDirective) can't find host element

I'm writing tests for a directive but I can't get the query for the directive host element to work using By.directive(IsRouteDirective). Console logging hostElement always yields null.

In the code below, LibRouteComponent and LibTestComponent are just dummy components with an empty template.

Here's the directive (short version):

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

export class IsRouteDirective implements OnInit { ... }

And here's the test setup for it:

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();
  });
});

Using By.css('div') gives DebugElement{nativeNode: <div libisroute=""></div>.... in the log which shows that the element exists and the directive selector is set on it.

I'm doing exactly what the offical docs are doing here.

Why doesn't By.directive(IsRouteDirective) work in my case?

like image 973
Chrillewoodz Avatar asked Dec 09 '25 05:12

Chrillewoodz


1 Answers

In my case I simply forgot to add the TestComponent to declarations of the TestBed module. It still allowed me to call createComponent(TestComponent) for it but wasn't able to query any components from its template

like image 108
Statyan Avatar answered Dec 10 '25 18:12

Statyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!