Модульный тест Angular Material Dialog - Как включить MAT_DIALOG_DATA - PullRequest
0 голосов
/ 06 декабря 2018

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

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

@Component({
    templateUrl: './confirmation-dialog.component.html',
    styleUrls: ['./confirmation-dialog.component.scss']
})
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();
    }));
});

Ошибка кармы

Karma Error Screenshot

Я сделал все возможное, чтобыищи этот вопрос и избегай дубликатов

Ответы [ 2 ]

0 голосов
/ 12 мая 2019

Вот пример, если мы вставим MAT_DIALOG_DATA в наш компонент:

 import { async, ComponentFixture, TestBed } from '@angular/core/testing';
 import { MatDialogModule } from '@angular/material/dialog'; // necesary to use components and directives of dialog module
 import { MAT_DIALOG_DATA } from '@angular/material'; // necesary for inject and recip incoming data

 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();
  });
});
0 голосов
/ 06 декабря 2018

попробуйте,

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