Angular Material and Jasmine : “ No provider for InjectionToken MdDialogData! ”

前端 未结 6 2028
醉梦人生
醉梦人生 2021-02-01 12:12

I have a component which is meant to be used in an Angular Material MdDialog :

@Component({
  ...
})
export class MyComponent {

  constructor(@Inject(MD_DIALOG_         


        
相关标签:
6条回答
  • 2021-02-01 12:29

    as an update, this is also replicated for those who use the tags with the prefix "Mat"

    providers: [{provide: MAT_DIALOG_DATA, useValue: {}}, 
    {provide: MatDialogRef, useValue: {}}]
    
    0 讨论(0)
  • 2021-02-01 12:31

    You can use Angular Optional decorator, I faced this problem before so

    if the component is not used as a popup try this snippet

    constructor(
      @Optional() public dialogRef: MatDialogRef<PopupComponent>,
      @Optional() @Inject(MAT_DIALOG_DATA) public data: any
    ) {}
    
    0 讨论(0)
  • 2021-02-01 12:39

    you can inject MAT_DIALOG_DATA / MAT_BOTTOM_SHEET_DATA in jasmine tests without specifying a provider. you must simply ensure that the value being injected is non-null. if it is null, the compiler mistakes the null value for a non-existing provider and you get the provider not found error.

    0 讨论(0)
  • 2021-02-01 12:52

    For Angular 5 with latest Material Component

     import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
    

    and

     providers: [
         { provide: MAT_DIALOG_DATA, useValue: {} },
         { provide: MatDialogRef, useValue: {} }
     ]
    
    0 讨论(0)
  • 2021-02-01 12:52

    try this

    beforeEach(async(() => {
     TestBed.configureTestingModule({
       imports: [
         SharedTestingModule,
       ],
       declarations: [
         MyComponent,
       ],
       providers: [ <-- here
        {
         provide: MdDialogData,
         useValue: {},
        }
       ] <-- to here 
     })
     .compileComponents();
    }));
    

    let me know how it goes

    0 讨论(0)
  • 2021-02-01 12:56

    I added this :

    providers: [
        { provide: MD_DIALOG_DATA, useValue: {} },
        { provide: MdDialogRef, useValue: {} }
    ]
    

    And it works :)

    Thanks for your help @methgaard!

    0 讨论(0)
提交回复
热议问题