具有相关性的Angular 7指令的Jest测试

时间:2019-08-19 15:58:08

标签: angular dependency-injection jestjs angular-directive angular-router

我有一个指令,必须将其添加到Angular 7 app.component的<router-outlet>中。当此指令将路由数据对象中包含的信息传递到当前托管Angular应用程序的外部(非Angular)应用程序时,该指令包括对Angular Router和DOCUMENT的依赖。我正在尝试为此编写单元测试,但是依赖注入没有运气。

我的指令如下所示:

@Directive({
  selector: '[addData]'
})
export class AddDataDirective {
  constructor(private router: Router, @Inject(DOCUMENT) private document: Document) {
      router.events.pipe(
          filter(event => event instanceof ActivationEnd)
      ).subscribe((event:{snapshot: ActivatedRouteSnapshot}) => {
          const myLabel = this.document.querySelector('#my_label');
          if (myLabel) {
              myLabel.textContent = event.snapshot.data.myData;
          }
      });
   }
}

当我为此进行测试时,我认为我需要以下内容:

  1. @Component,带有选择器“ test-root”和模板 <router-outlet addData></router-outlet>
  2. @我要测试的路线的组件(可以有任何模板)
  3. 包含来自#2的组件以及我需要传递的数据的Routes数组
  4. 一个模拟文档,其中包含以某种方式引用了#1组件的模板

我目前已经设置了2个组件,以及路由以及对提供路由器和DOCUMENT的模拟文档和TestBed的开始。但是,当我运行此命令时,我最终在TestBedViewEngine._createCompilerAndModule中收到错误消息,提示“无法读取null的属性'injector'”:

const doc = `<div><test-root></test-root><h1 id="my_label"></h1></div>`;
const routes: Routes = [
  ...
];
const testPath = 'test';
const pathName = `/${testPath}`;
const mockDocument = jest.mock('@angular/common', () => ({
  DOCUMENT: {location: {pathName}}
})); 

在beforeEach中,我的TestBed设置如下:

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        AddDataDirective, 
        TestComponent,
        AppComponent
      ],
      imports: [RouterTestingModule.withRoutes(routes)],
      providers: [
        { provide: Router, useValue: {events: of(activationEvent)}},
        { provide: DOCUMENT, useValue: mockDocument }
      ]
    });

    fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();

    document.body.insertAdjacentHTML('afterbegin', doc);    
  }); 

我还需要在提供者部分添加其他内容吗?我什至不确定哪个注入器发生故障-路由器或文档。

0 个答案:

没有答案