MAT_DIALOG_DATA的角度测试依赖性注入

时间:2018-07-25 14:18:45

标签: angular unit-testing karma-jasmine

我有一个像这样的应用程序组件,我想为此编写一个单元测试。

   export class AppComponent {
        public errorCode = new BehaviorSubject<number | null>(null);
        public isLoading = new BehaviorSubject<boolean>(false);

        constructor(
            public dialogRef: MatDialogRef<NotificationDeleteDialogComponent>,
            private notificationService: NotificationService,
            @Inject(MAT_DIALOG_DATA) public data: any
        ) { }
}

如何做DI,是指如何将这些构造函数类导入测试文件并注入数据。

谢谢

1 个答案:

答案 0 :(得分:0)

您只需要在TestBed中提供构造函数参数,就像这样:

beforeEach(async(() => {
    TestBed.configureTestingModule({
        declarations: [ AppComponent ],
        providers: [
            { provide: MatDialogRef, useValue: { close: () => {} } },
            { provide: notificationService, useValue: mockedNotificationService},
            { provide: MAT_DIALOG_DATA, useValue: mockedDialogData },
        ]
    }).compileComponents();
}));

beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    matDialogRef = fixture.debugElement.injector.get(MatDialogRef);
    notificationService = fixture.debugElement.injector.get(NotificationService);

    fixture.detectChanges();
});

不要忘记用测试中需要的内容声明mockedNotificationServicemockedDialogData