web-dev-qa-db-fra.com

Test unitaire Angular Dialogue Material - Comment inclure MAT_DIALOG_DATA

J'essaie de tester unitairement cette boîte de dialogue de matériau pour tester si le modèle rend le bon objet injecté. Le composant fonctionne correctement lorsqu'il est utilisé correctement

Composant - La boîte de dialogue

export class ConfirmationDialogComponent {

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

Modèle de boîte de dialogue

<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>

Modèle - Qu'est-ce qui est injecté

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

Test unitaire - Où je reçois le problème

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();
  }));
});

Erreur de karma

Karma Error Screenshot

7
Erik

Voici un exemple de la façon d'injecter MAT_DIALOG_DATA dans un test unitaire:

 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();
  });
});