最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to test angular material dialog? - Stack Overflow

programmeradmin4浏览0评论

I have a custom dialog component class which I am trying to test. Specifically my close function which is this

  close(): void {
    this.dialogRef.close();
  }

dialogRef is injected in that classes constructor as shown below

 constructor(public dialogRef: MatDialogRef<CustomDialogComponent>,
              @Inject(MAT_DIALOG_DATA) public data: any) {
  }

So my question would be, how could I mock dialogRef in my spec test file and test its close function?

My project is using angular 5, and angular material 5.

I have a custom dialog component class which I am trying to test. Specifically my close function which is this

  close(): void {
    this.dialogRef.close();
  }

dialogRef is injected in that classes constructor as shown below

 constructor(public dialogRef: MatDialogRef<CustomDialogComponent>,
              @Inject(MAT_DIALOG_DATA) public data: any) {
  }

So my question would be, how could I mock dialogRef in my spec test file and test its close function?

My project is using angular 5, and angular material 5.

Share Improve this question edited Jan 8, 2018 at 20:16 charlietfl 172k13 gold badges125 silver badges151 bronze badges asked Jan 8, 2018 at 18:45 FernandoFernando 4601 gold badge7 silver badges22 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 14

Assuming that you are asking about testing components that use dialog and not dialog itself, In your test case, add

providers: [
     { provide: MAT_DIALOG_DATA, useValue: {} },
     { provide: MatDialogRef, useValue: {} }
 ]

That should provide neccessary dependencies.

You shouldn't need to test this because the library you are using should already test its own component (which is not always the case).

But if you need a specific test which uses the close dialog reference, have a look at their test on this component which should help you write yours :

https://github.com/angular/components/blob/master/src/material/dialog/dialog.spec.ts#L186

发布评论

评论列表(0)

  1. 暂无评论