使用调用服务的构造方法测试应用程序组件

时间:2019-01-10 14:09:56

标签: angular unit-testing jasmine karma-jasmine

我有一个angular 7应用程序,我正在尝试学习如何正确测试我的应用程序。

当前在我的应用程序component.ts中,我有一个警报服务,该服务用于显示作为动态组件的对话框。

export class AppComponent {

    constructor(private alertService: AlertHelperService,
                private viewContainerRef: ViewContainerRef){
                   alertService.setRootViewContainerRef(viewContainerRef);
                   alertService.AddAlertComponent();
                  }
}

我设置了标准测试来检查应用程序是否正确初始化:

    describe('AppComponent', () => {
      let mockAlertHelperService;
      beforeEach(async(() => {
        let alertService: AlertHelperService;
        mockAlertHelperService - jasmine.createSpyObj(['setRootViewContainerRef', 'AddAlertComponent']);

        TestBed.configureTestingModule({
          imports: [
            RouterTestingModule,
            FontAwesomeModule,
          ],
          declarations: [
            AppComponent,
            ToastComponent,
            AlertComponent
          ],
          providers: [
            { provide: AlertHelperService, useValue: mockAlertHelperService }

                ]
        }).compileComponents();
      }));

       it('should create the app', () => {
         const fixture = TestBed.createComponent(AppComponent);
         const app = fixture.debugElement.componentInstance;
         alertService = TestBed.get(AlertHelperService);
         expect(app).toBeTruthy();
  });

我想单独测试组件。但是,运行测试时出现此错误:

  

错误:找不到AlertComponent的组件工厂。您是否将其添加到@ NgModule.entryComponents?

我知道这是说找不到AlertComponent。我将其导入服务中,因此不确定为什么会发生这种情况:

import { Injectable, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';
import { AlertComponent } from './alert.component';

    @Injectable({
       providedIn: 'root'
    })
    export class AlertHelperService {

      rootViewContainer: ViewContainerRef;

      constructor(private factoryResolver: ComponentFactoryResolver) { }


      setRootViewContainerRef(viewContainerRef: ViewContainerRef) {
        this.rootViewContainer = viewContainerRef;
      }

      AddAlertComponent() {
        const factory = this.factoryResolver.resolveComponentFactory(AlertComponent);
        const component = factory.create(this.rootViewContainer.parentInjector);
        this.rootViewContainer.insert(component.hostView);
      }
    }

我尝试导入它,声明它以及其他各种方法,但没有任何效果。总是一样的错误

0 个答案:

没有答案