本文介绍了Angular:如何在测试时模拟 MatDialogRef的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 DialogComponent
,它具有以下构造函数,其中 Dialog
是一个自定义对象:
I have a DialogComponent
that has the following constructor where Dialog
is a custom object:
constructor(
public dialogRef: MatDialogRef<CustomDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: Dialog
)
我在 Angular4 中创建了以下 TestBed
:
I created the following TestBed
in Angular4:
data = new Dialog()
data.message = 'Dialog Message'
TestBed.configureTestingModule({
imports: [MaterialModules],
declarations: [CustomDialogComponent],
providers: [MatDialogRef, { provide: Dialog, useValue: data }]
})
TestBed.overrideModule(BrowserDynamicTestingModule, {
set: {
entryComponents: [CustomDialogComponent]
}
})
await TestBed.compileComponents()
但我收到以下错误:
Failed: Can't resolve all parameters for MatDialogRef: (?, ?, ?).
Error: Can't resolve all parameters for MatDialogRef: (?, ?, ?).
将提供商更改为:
providers: [
{ provide: MatDialogRef, useValue: {} },
{ provide: MAT_DIALOG_DATA, useValue: data }
]
导致以下错误:
Error: No provider for Dialog!
我该如何解决这个问题?
How do I resolve this?
推荐答案
我通过将组件构造函数更改为:
I solved it by changing the component constructor to:
constructor(
public dialogRef: MatDialogRef<CustomDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: Dialog | any
)
TestBed 中的提供者是:
The providers in the TestBed were:
providers: [{ provide: MatDialogRef, useValue: {} }, { provide: MAT_DIALOG_DATA, useValue: data }]
这篇关于Angular:如何在测试时模拟 MatDialogRef的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!