如何在测试时模拟MatDialogRef

如何在测试时模拟MatDialogRef

本文介绍了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!

我该如何解决?

推荐答案

我通过将组件构造函数更改为:

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 20:52