我通过以下方式创建了一个全新的组件:
ng g mytest1
然后我将构造函数行更改为:
constructor(private dialogRef: MatDialogRef<Mytest1Component>) { }
,并添加了所需的导入:
import { MatDialogRef } from '@angular/material';
之后,我通过以下方式运行 Karma 单元测试项目:
ng test
测试失败。我收到此错误消息:
Error: StaticInjectorError(DynamicTestModule)[Mytest1Component -> MatDialogRef]: StaticInjectorError(Platform: core)[Mytest1Component -> MatDialogRef]: NullInjectorError: No provider for MatDialogRef!
为了解决这个问题,我在 beforeEach 部分中添加了 Import 语句:
import { MatDialogRef } from '@angular/material';
//...
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ Mytest1Component ],
imports: [MatDialogRef],
})
.compileComponents();
}));
现在我得到了这个新错误,我无法修复:
Failed: Unexpected value 'MatDialogRef' imported by the module 'DynamicTestModule'. Please add a @NgModule annotation.
有人可以澄清我应该在哪里添加 @NgModule 注释,或者我做错了什么?
谢谢你。
最佳答案
您正在注入(inject) MatDialogRef
在组件中:
constructor(private dialogRef: MatDialogRef<Mytest1Component>) { }
所以 testBed 期望注入(inject)与
provider
相同的内容。到测试床。或者您也可以提供MockDialogueService
给它。beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ Mytest1Component ],
providers: [ MatDialogRef ],
})
.compileComponents();
}));
关于angular - Karma 单元测试错误 : Unexpected value imported by the module. 请添加@NgModule 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54772990/