简体   繁体   English

如何测试角度7 karma测试中是否动态加载组件?

[英]How to test whether a component is dynamically loaded in angular 7 karma tests?

I have made a component in which I am dynamically loading another component which is working fine on ng serve . 我已经创建了一个组件,我在其中动态加载另一个在ng serve上正常工作的组件。 Below is the code for dynamically loading the component. 下面是动态加载组件的代码。

import { Component, OnInit, ViewChild, ComponentFactoryResolver, Type, Input} from '@angular/core';
import { AddComponentDirective } from '../add-component.directive';
import { DynamicComponent } from '../dynamic/dynamic.component';
import { ComponentData } from '../component-data';
import { ComponentItem } from '../component-item';

  export class DynamicLoaderComponent implements OnInit {
      @ViewChild (AddComponentDirective) adhost : AddComponentDirective;

      constructor(private componentFactoryResolver : ComponentFactoryResolver) { }

      ngOnInit() {
          this.loadComponent(DynamicComponent,message,this.adhost);
      }

      loadComponent(comp, message, host){
          let adItem = new ComponentItem(comp,{msg: message});
          let componentFactory = this.componentFactoryResolver.resolveComponentFactory(adItem.component);
          let viewContainerRef = host.viewContainer;
          let componentRef = viewContainerRef.createComponent(componentFactory);
      (<ComponentData>componentRef.instance).data = adItem.data;
    }
 }

But while testing it with angular karma test, we are facing type error ie 但是在使用角度业力测试进行测试时,我们面临着类型错误,即

TypeError: this.componentFactoryResolver.resolveComponentFactory is not a function TypeError:this.componentFactoryResolver.resolveComponentFactory不是函数

Below is the spec.ts file how I am testing it. 下面是spec.ts文件,我是如何测试它的。

import { async, ComponentFixture, TestBed ,getTestBed,inject} from '@angular/core/testing';
import {ComponentFactoryResolver,ViewChild,DebugElement} from '@angular/core';
import { AddComponentDirective } from '../add-component.directive';
import { DynamicComponent } from '../dynamic/dynamic.component';
import { DynamicLoaderComponent } from './dynamic-loader.component';
import { BrowserDynamicTestingModule } from "@angular/platform-browser-dynamic/testing";
import { ComponentData } from "../component-data";

describe('DynamicLoaderComponent', () => {
  let component: DynamicLoaderComponent;
  let fixture: ComponentFixture<DynamicLoaderComponent>;
  let injector: TestBed;
  let componentFactoryResolver : ComponentFactoryResolver ;
  let debugElement: DebugElement

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ DynamicLoaderComponent,AddComponentDirective ,DynamicComponent],
      providers:[DynamicLoaderComponent,ComponentFactoryResolver]
    })
    .compileComponents();

    TestBed.overrideModule(BrowserDynamicTestingModule, {
      set: {
        entryComponents: [DynamicComponent]
      }
    });

  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(DynamicLoaderComponent);
    component = fixture.componentInstance;
    componentFactoryResolver =  fixture.debugElement.injector.get(ComponentFactoryResolver);
    fixture.detectChanges();
  });  

  it('should create the DynamicLoaderComponent',inject([DynamicLoaderComponent], (component : DynamicLoaderComponent) => {
    expect(component).toBeTruthy();
  }));

});

附加了浏览器上测试文件错误的图像。点击查看

Can you help me solve this issue so that I can proceed further in the testing of dynamic components? 你能帮我解决这个问题,以便我可以进一步测试动态组件吗?

There are several changes you need to make to fix those errors: 您需要进行一些更改才能修复这些错误:

1) Remove providers from TestBed configuration 1)从TestBed配置中删除providers

TestBed.configureTestingModule({
  declarations: [ DynamicLoaderComponent,AddComponentDirective ,DynamicComponent],
  providers:[DynamicLoaderComponent,ComponentFactoryResolver] <== remove this line
})

2) You do not need to get your component from DI, 2)您不需要从DI获取组件,

so replace 所以更换

it('should create the DynamicLoaderComponent', inject([DynamicLoaderComponent], (component : DynamicLoaderComponent) => {
  expect(component).toBeTruthy();
}));

with: 有:

it('should create the DynamicLoaderComponent', () => {
  expect(component).toBeTruthy();
});

3) compileComponents() call is only needed if you run tests in a non-CLI environment. 3)只有在非CLI环境中运行测试时才需要compileComponents()调用。

From Angular doc 来自Angular doc

Calling compileComponents() closes the current TestBed instance to further configuration. 调用compileComponents()会关闭当前的TestBed实例以进一步配置。 You cannot call any more TestBed configuration methods, not configureTestingModule() nor any of the override... methods. 您不能再调用任何TestBed配置方法,不能调用configureTestingModule(),也不能调用任何override ...方法。 The TestBed throws an error if you try. 如果你尝试,TestBed会抛出一个错误。

That means that your TestBed.overrideModule call won't have any effect and DynamicComponent 's factory won't be found. 这意味着您的TestBed.overrideModule调用将不会产生任何影响,并且将找不到DynamicComponent的工厂。

So remove .compileComponents(); 所以删除.compileComponents();

TestBed.configureTestingModule({
  declarations: [ DynamicLoaderComponent,AddComponentDirective ,DynamicComponent],
  providers:[DynamicLoaderComponent,ComponentFactoryResolver]
})
.compileComponents(); <==== remove this

If you're on non-angular-cli environment then you can call it after overriding module: 如果你在非angular-cli环境中,那么你可以在覆盖模块后调用它:

TestBed.overrideModule(BrowserDynamicTestingModule, {
  set: {
    entryComponents: [DynamicComponent]
  }
});

TestBed.compileComponents(); <== this line

After all changes I've written above, the test should be executed without any errors. 在我上面写的所有更改之后,应该执行测试而没有任何错误。

Plunker Example Plunker示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Karma for Angular中使用Froala编辑器测试组件? - How to test a component with Froala Editor in Karma for Angular? 如何在Angular2 Jasmine测试中对测试是否加载进行单元测试 - How to unit test whether a test is loaded or not in Angular2 Jasmine test Angular 2 测试业力。 究竟要测试什么 - Angular 2 tests karma. What exactly to test Karma-Jasmine 如何在 angular 中测试一个路由器组件 - Karma-Jasmine How to test in angular a Router component 由于 Angular Karma Jasmine 测试结果,在测试中看不到我的组件 - Can't see my component in Tests because of Angular Karma Jasmine test results 模拟测试组件的指令 - Angular 8 with jasmine 和 Karma - Mocking a Directive to Test a Component - Angular 8 with jasmine and Karma 如何让Karma在工作区内运行特定角度6组件库的测试 - How to get Karma to run tests of a specific angular 6 component library inside workspace Angular 6单元测试:如何使用test.ts进行业力测试 - Angular 6 Unit testing : how to use test.ts for running karma tests Angular 2 - 如何将id属性设置为动态加载的组件 - Angular 2 - How to set id attribute to the dynamically loaded component 如何在角度2中为动态加载的子组件提供父模型? - How to provide a parent's model to a dynamically loaded child component in angular 2?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM