如何在测试模块中注入MatDialog?

时间:2019-05-24 21:02:13

标签: angular jasmine angular-material

我向组件添加了一个MatDialog,现在所有单元测试都因

失败
  

错误:   StaticInjectorError(DynamicTestModule)[BiqWorkflowEditorComponent->   MatDialog]:StaticInjectorError(平台:   核心)[BiqWorkflowEditorComponent-> MatDialog]:       NullInjectorError:MatDialog没有提供程序!

我的组件

 constructor(public dialog: MatDialog, private renderer: Renderer2, private logService: LogService)

我的对话框

 constructor(
    public dialogRef: MatDialogRef<VisualPropertiesModalComponent>,
    @Inject(MAT_DIALOG_DATA) public data: Dictionary<string, string>)
  {
  }

我的测试

import {MatDialogModule} from '@angular/material/dialog';

describe('BiqWorkflowEditor.Component', () =>
{
  let component: BiqWorkflowEditorComponent;
  let fixture: ComponentFixture<BiqWorkflowEditorComponent>;
  let dialog: MatDialog;

  beforeEach(async(() =>
  {
    TestBed.configureTestingModule({
      declarations: [
        BiqWorkflowEditorComponent,
      ],
      imports: [
        MatDialogModule
      ],
      providers: [ 
        MatDialog
      ]
    })
    .compileComponents();
  }));

  beforeEach(() =>
  {
    fixture = TestBed.createComponent(BiqWorkflowEditorComponent);
    component = fixture.componentInstance;

    dialog = TestBed.get(MatDialog);

    fixture.detectChanges();
  });

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

2 个答案:

答案 0 :(得分:0)

尝试一下(您需要一个模拟提供程序):

import {MatDialogModule} from '@angular/material/dialog';

describe('BiqWorkflowEditor.Component', () =>
{
  let component: BiqWorkflowEditorComponent;
  let fixture: ComponentFixture<BiqWorkflowEditorComponent>;
  let dialog: MatDialog;
  const mockMatDialog = {
    closeAll: (): void => undefined
  };
  beforeEach(async(() =>
  {
    const mockProviders: Provider[] = [
        { provide: MatDialog, useValue: mockMatDialog }
      ];
    TestBed.configureTestingModule({
      declarations: [
        BiqWorkflowEditorComponent,
      ],
      imports: [
        MatDialogModule
      ],
      providers: mockProviders
    })
    .compileComponents();
  }));

  beforeEach(() =>
  {
    fixture = TestBed.createComponent(BiqWorkflowEditorComponent);
    component = fixture.componentInstance;

    dialog = TestBed.get(MatDialog);

    fixture.detectChanges();
  });

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

答案 1 :(得分:0)

实际上,我所讨论的共享代码可以正常工作,问题是在将其固定在一个文件中后,我在另一个测试文件中遇到了相同的错误,但是我没有注意到它在另一个文件中发生。对不起,误报警:(。

相关问题