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

痞子三分冷 提交于 2020-01-11 21:10:00

问题


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

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

  constructor(@Inject(MD_DIALOG_DATA) public data: any, public dialogRef: 
MdDialogRef<MyComponent>) {
...
  }


}

I am trying to Unit Test it with Jasmine :

describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        SharedTestingModule,
      ],
      declarations: [
        MyComponent,
      ],
    })
    .compileComponents();
  }));

  ...

});

Unfortunately, I am getting the following error :

Error: No provider for InjectionToken MdDialogData!

SharedTestingModule imports and exports my custom Angular Material module, which itself imports and exports MdDialogModule.

How can I get rid of this error?

Thank you very much!

Angular 4.2.4
Angular Material 2.0.0-beta.7
Jasmine 2.5.3

回答1:


I added this :

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

And it works :)

Thanks for your help @methgaard!




回答2:


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: {} }
 ]



回答3:


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: {}}]



回答4:


try this

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

let me know how it goes




回答5:


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.



来源:https://stackoverflow.com/questions/44826518/angular-material-and-jasmine-no-provider-for-injectiontoken-mddialogdata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!