我正在尝试为 MatDialog 编写一些单元测试。我想要做的是模拟来自对话框的响应并测试它是否被组件正确处理。
在我的组件中,我应该Map<string, any>
从关闭的对话框中获取一个并将它们设置为myData
Map。
我的.component.ts
export class MyComponent {
public myData = new Map<string, any>();
constructor(public dialog: MatDialog) { }
public openDialog(): void {
const dialogRef = this.dialog.open(LoadDataComponent);
dialogRef.afterClosed().subscribe(response => {
response.data.forEach(item => {
this.myData.set(item.id, item);
});
});
}
}
我的.component.spec.ts
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
const responseMock = new Map<string, any>();
class DialogMock {
open(): any {
return {
afterClosed: () => of(responseMock)
};
}
}
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [
MyComponent
],
providers: [
{ provide: MatDialog, useClass: DialogMock },
]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
component.myData = new Map<string, any>();
fixture.detectChanges();
responseMock.set('test', {value: 'test'});
responseMock.set('test2', {value: 'test2'});
});
it('should get data from dialog', fakeAsync(() => {
spyOn(component.dialog, 'open').and.returnValue({
afterClosed: () => of(responseMock)
} as MatDialogRef<typeof component>);
component.openDialog();
expect(component.myData.size).toBe(2);
}));
});
在我的规范文件中,我创建了一些responseMock
,我试图将其用作响应,但我的测试只是失败了:
Chrome Headless 91.0.4472.164(Windows 10)错误在 afterAll TypeError 中引发错误:无法读取未定义
Chrome 91.0.4472.164(Windows 10)的属性“forEach”MyComponent 应从对话框 FAILED 错误中获取数据:预期 0 为 2。
如何在单元测试中模拟来自 MatDialog 的响应,以便正确处理MyComponent
?