角质材料和茉莉花: “没有提供注入令牌 MdDialogData!”

我有一个组件,它是用来在一个角度材质 MdDialog 中使用的:

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


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




}

我正在尝试用 Jasmine 对它进行单元测试:

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


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


...
  

});

不幸的是,我得到了以下错误:

错误: 没有 InjectionToken MdDialogData 的提供程序!

SharedTestingModule 导入和导出我的自定义角度材料模块,该模块本身导入和导出 MdDialogModule。

我怎样才能消除这个错误?

非常感谢!

Angular 4.2.4
Angular Material 2.0.0-beta.7
Jasmine 2.5.3
86367 次浏览

try this

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

let me know how it goes

I added this :

providers: [
{ provide: MAT_DIALOG_DATA, useValue: {} },
// { provide: MdDialogRef, useValue: {} }, --> deprecated
{ provide: MatDialogRef, useValue: {} } ---> now
]

And it works :)

Thanks for your help @methgaard!

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

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

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.

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
) {}

try add in your <x>.component.spec.ts under providers:

{ provide: MatDialog, useValue: {} }

in some cases you need also:

{ provide: MatDialogRef, useValue: {} }

(this way working in my angular 11 project)

No provider for InjectionToken MatDialogData!, This error will occur when we run test cases, When we use matdialog reference with @Inject(MAT_DIALOG_DATA) public value: string, in the respected component.

Add below code in spec.ts file

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