Диалог модульного теста Angular Material - как включить MAT_DIALOG_DATA

Я пытаюсь выполнить модульное тестирование этого диалогового окна материала, чтобы проверить, правильно ли отображается введенный объект в шаблоне. Компонент отлично работает при правильном использовании

Компонент - Диалог

export class ConfirmationDialogComponent {

  constructor(@Inject(MAT_DIALOG_DATA) private dialogModel: ConfirmationDialogModel) {}
}

Шаблон диалога

<h1 mat-dialog-title *ngIf="dialogModel.Title">{{dialogModel.Title}}</h1>
<div mat-dialog-content>
  {{dialogModel.SupportingText}}
</div>
<div mat-dialog-actions>
  <button mat-button color="primary" [mat-dialog-close]="false">Cancel</button>
  <button mat-raised-button color="primary"[mat-dialog-close]="true" cdkFocusInitial>{{dialogModel.ActionButton}}</button>
</div>

Модель - Что вводится

export interface ConfirmationDialogModel {
  Title?: string;
  SupportingText: string;
  ActionButton: string;
}

Модульный тест - где возникает проблема

describe('Confirmation Dialog Component', () => {

  const model: ConfirmationDialogModel = {
    ActionButton: 'Delete',
    SupportingText: 'Are you sure?',
  };

  let component: ConfirmationDialogComponent;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        ConfirmationDialogComponent
      ],
      imports: [
        MatButtonModule,
        MatDialogModule
      ],
      providers: [
        {
          // I was expecting this will pass the desired value
          provide: MAT_DIALOG_DATA,
          useValue: model
        }
      ]
    });

    component = TestBed.get(ConfirmationDialogComponent);
  }));

  it('should be created', async(() => {
    expect(component).toBeTruthy();
  }));
});

Карма ошибка

Скриншот ошибки кармы


person Erik    schedule 06.12.2018    source источник


Ответы (2)


Попробуй это:

describe('Confirmation Dialog Component', () => {
    
  const model: ConfirmationDialogModel = {
    ActionButton: 'Delete',
    SupportingText: 'Are you sure?',
  };
    
  let component: ConfirmationDialogComponent;
  let fixture: ComponentFixture<ConfirmationDialogComponent>;
    
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        ConfirmationDialogComponent
      ],
      imports: [
        MatButtonModule,
        MatDialogModule
      ],
      providers: [
        {
          // I was expecting this will pass the desired value
          provide: MAT_DIALOG_DATA,
          useValue: model
        }
      ]
    })
      .compileComponents();
            
  }));
    
        
  beforeEach(() => {
    fixture = TestBed.createComponent(ConfirmationDialogComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });
    
  it('should be created', async(() => {
    expect(component).toBeTruthy();
  }));

  it('should close dialog when close button clicked', fakeAsync(() => {
    component.onCloseButtonClicked(0);
    fixture.detectChanges();
    tick();
    expect(mockMainDialogRef.close.calls.count()).toBe(1, 'dialog closed');
  }));
});
person Indrakumara    schedule 06.12.2018
comment
Кроме того, если вы используете MatDialogRef в своем компоненте, вам необходимо включить его в массив providers. Пример: JavaScript providers: [{ provide: MatDialogRef, useValue: { close: (dialogResult: any) => { } } }] исходный код - person Netanel Draiman; 25.02.2019
comment
Как мне нужно тестировать что-то вроде should be closed? - person utdev; 26.08.2020
comment
@utdev Я обновил ответ с помощью закрытого модульного теста - person Indrakumara; 26.08.2020

Вот пример того, как ввести MAT_DIALOG_DATA в модульном тесте:

 import { async, ComponentFixture, TestBed } from '@angular/core/testing';
 import { MatDialogModule, MAT_DIALOG_DATA } from '@angular/material/dialog';

 import { ConfirmDialogComponent } from './confirm-dialog.component';

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

   beforeEach(async(() => {
     TestBed.configureTestingModule({
       declarations: [ ConfirmDialogComponent ],
       imports: [ MatDialogModule ], // add here
       providers: [
        { provide: MAT_DIALOG_DATA, useValue: {} } // add here
      ],
    })
    .compileComponents();
  }));

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

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});
person Daniel Delgado    schedule 12.05.2019