如何模拟 Angular 单元测试中从 afterClosed 发送的 MatDialog 的响应?

How to mock a response from MatDialog sent from afterClosed in Angular unit tests?

我正在尝试为 MatDialog 编写一些单元测试。我想做的是模拟对话框的响应并测试它是否被组件正确处理。

在我的组件中,我应该从关闭的对话框中获取 Map<string, any> 并将它们设置到 myData 地图中。

my.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);
        });
    });
  }
}

my.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) ERROR An error was thrown in afterAll TypeError: Cannot read property 'forEach' of undefined
Chrome 91.0.4472.164 (Windows 10) MyComponent should get data from dialog FAILED Error: Expected 0 to be 2.

如何在我的单元测试中模拟来自 MatDialog 的响应,以便 MyComponent 正确处理它?

在测试的方法中,有一个针对响应数据的循环:response.data.forEach。根据模拟设置,response 的值将是 const responseMock = new Map<string, any>();。它不包含 data 属性。要修复它,您可以将响应模拟更改为

const responseMock = {data: new Map<string, any>()};