Angular 将嵌套组件作为MatDialog内容的单元测试组件
我想对显示项目列表的角度组件进行单元测试。在某些情况下,它会显示一个编辑按钮来编辑特定项目,并提供一个添加按钮来添加新项目。 编辑和添加通过显示Angular 将嵌套组件作为MatDialog内容的单元测试组件,angular,unit-testing,testbed,mat-dialog,Angular,Unit Testing,Testbed,Mat Dialog,我想对显示项目列表的角度组件进行单元测试。在某些情况下,它会显示一个编辑按钮来编辑特定项目,并提供一个添加按钮来添加新项目。 编辑和添加通过显示ItemFormComponent的模式完成。此组件有一个注入的依赖项ItemService,它将更改持久化到后端。对话框的结果是新的或编辑的项目,因此ListViewComponent可能会在必要时更新其内容 在测试ListViewComponent时,我面临模拟MatDialog部分的问题 我的第一个想法是为ItemService提供一个mock,但
ItemFormComponent
的模式完成。此组件有一个注入的依赖项ItemService
,它将更改持久化到后端。对话框的结果是新的或编辑的项目,因此ListViewComponent
可能会在必要时更新其内容
在测试ListViewComponent
时,我面临模拟MatDialog部分的问题
我的第一个想法是为ItemService
提供一个mock,但是测试启动失败,因为它无法在真实的ItemService
中找到环境变量提供的参数,因此没有向ItemFormComponent
提供mock
这是我的代码:
describe("ListViewComponent", () => {
let component: ListViewComponent;
let fixture: ComponentFixture<ListViewComponent>;
let itemServiceSpy: jasmine.SpyObj<ItemService>;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ListViewComponent],
providers: [
{provide: ItemService, useValue: itemServiceSpy}
]
})
.compileComponents();
itemServiceSpy = TestBed.inject(ItemService) as jasmine.SpyObj<ItemService>;
fixture = TestBed.createComponent(ListViewComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it("should create", () => {
expect(component).toBeTruthy();
});
description(“ListViewComponent”,()=>{
let组件:ListViewComponent;
let夹具:组件夹具;
让itemServiceSpy:jasmine.SpyObj;
在每个之前(()=>{
TestBed.configureTestingModule({
声明:[ListViewComponent],
供应商:[
{提供:ItemService,useValue:itemServiceSpy}
]
})
.compileComponents();
itemServiceSpy=TestBed.inject(ItemService)作为jasmine.SpyObj;
fixture=TestBed.createComponent(ListViewComponent);
组件=fixture.componentInstance;
fixture.detectChanges();
});
它(“应该创建”,()=>{
expect(component.toBeTruthy();
});
}))
对话框的实例化是通过
this.dialogRef = this.matDialog.open<ItemFormComponent>(ItemFormComponent, {
data: {
item: item
}
});
this.dialogRef=this.matDialog.open(ItemFormComponent{
数据:{
项目:项目
}
});
我认为更好的方法是完全模拟MatDialog部分,这样我可以伪造对话框结果并检查ListViewComponent
的行为
但我不知道如何解决这个问题
欢迎任何提示或解决方案建议,谢谢
亲切问候,,
安德烈亚斯