单元测试MatDialog

时间:2019-01-10 03:17:12

标签: javascript angular typescript karma-jasmine

我正在为使用MatDialog的确认模式创建单元测试。我的第一个测试是应该创建组件的基本测试。这是我的规范文件代码。

import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { PocitConfirmationModalComponent } from './confirmation-modal.component';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { CommonModule } from '@angular/common';
import { PortalModule } from '@angular/cdk/portal';
import { MaterialModule } from 'src/app/core/material/material.module';
import { BrowserDynamicTestingModule } from '@angular/platform-browser-dynamic/testing';


class MatDialogRefStub {
    close(param: string) {}
}

describe('PocitConfirmationModalComponent', () => {
  let component: PocitConfirmationModalComponent;
  let fixture: ComponentFixture<PocitConfirmationModalComponent>;


  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        CommonModule,
        MaterialModule,
        PortalModule
       ],
      declarations: [PocitConfirmationModalComponent],
      providers: [
          { provide: MatDialogRef, useClass: MatDialogRefStub },
          { provide: MAT_DIALOG_DATA, useValue: {} },
      ]
    }).overrideModule(BrowserDynamicTestingModule, {
        set: {
          entryComponents: [ PocitConfirmationModalComponent ],
        }
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(PocitConfirmationModalComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

});

这是我要测试的组件文件。

import { Component, OnInit, Inject, ViewEncapsulation } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { ComponentPortal } from '@angular/cdk/portal';

@Component({
  selector: 'pocit-confirmation-modal',
  templateUrl: './confirmation-modal.component.html',
  styleUrls: ['./confirmation-modal.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class PocitConfirmationModalComponent implements OnInit {

  portal: ComponentPortal<any>;

  constructor(
    public dialogRef: MatDialogRef<PocitConfirmationModalComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any,
  ) {
    this.portal = new ComponentPortal(this.data.component);
   }

  ngOnInit() {
  }

  action(type: string) {
    this.dialogRef.close(type);
  }

}

所有这些之后,我在运行测试后得到了此错误。

Error: No component factory found for undefined. Did you add it to @NgModule.entryComponents?

我已经将其添加到entryComponents中,但仍然出现此错误。

1 个答案:

答案 0 :(得分:0)

    //your public data:any model, eg:
const model: any = {
    ActionButton: 'Delete',
    SupportingText: 'Are you sure?',
  };

然后在提供程序中

providers: [
        {              
          provide: MAT_DIALOG_DATA,
          useValue: model
        }
      ]