首页 > 解决方案 > 如何测试 Angular Material 对话框是否打开

问题描述

我正在编写一个单元测试来检查函数调用是否打开了 Material 对话框元素。我得到了 False,而预期的结果是 True。组件功能为:

x.component.ts

openCartDialog(): void {
        this.dialog.open(CartComponent);
        this.isCartDialogOpen = true;
}

我的 x.component.spec.ts 文件有以下代码和测试:

export class DialogMock {
    open(): void {
        return;
    }
}

beforeEach(async(() => {

    TestBed.configureTestingModule({
        declarations: [MainPageComponent, CartComponent, ConfirmButtonComponent],
        imports: [RouterTestingModule, HttpClientModule, MatTabsModule, MatDialogModule],
        providers: [
            { provider: MatDialog, useClass: DialogMock },
        ],
    }).compileComponents();
}));

beforeEach(() => {
    fixture = TestBed.createComponent(MainPageComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
});


it('should open the cart dialog', () => {
       component.openCartDialog();
       expect(component.isCartDialogOpen).toBeTrue();
});

我认为问题出在我的 beforeEach() 中 CartComponent 没有正确实例化。Cart 组件在其模板中也使用了其他组件...我在这段代码中只包含了 ConfirmButtonComponent,但还有更多。

谢谢你的帮助!

标签: angularangular-materialangular-test

解决方案


推荐阅读