【问题标题】:Angular - fixture.debugElement.query(By.directive(IsRouteDirective) can't find host elementAngular-fixture.debugElement.query(By.directive(IsRouteDirective)找不到宿主元素
【发布时间】:2019-10-03 14:15:40
【问题描述】:

我正在为指令编写测试,但无法使用 By.directive(IsRouteDirective) 查询指令宿主元素。控制台日志记录 hostElement 总是产生 null

在下面的代码中,LibRouteComponentLibTestComponent 只是带​​有空模板的虚拟组件。

这是指令(短版):

@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: &lt;div libisroute=""&gt;&lt;/div&gt;....,这表明该元素存在并且在其上设置了指令选择器。

我正在做官方文档正在做的事情here

为什么By.directive(IsRouteDirective) 在我的情况下不起作用?

【问题讨论】:

    标签: angular unit-testing jasmine angular-directive


    【解决方案1】:

    解决方法

    fixture.debugElement.query(By.directive(IsRouteDirective)).injector.get(IsRouteDirective)

    【讨论】:

      猜你喜欢
      • 2016-10-19
      • 1970-01-01
      • 2018-06-21
      • 1970-01-01
      • 2016-04-11
      • 1970-01-01
      • 2018-05-12
      • 2018-08-03
      • 2022-12-09
      相关资源
      最近更新 更多