需求: 项目中使用了 MatDialog 来弹出一个组件的功能。需要测试当前弹出页面和弹出组件之间的交互功能。
直接上代码。
//spec.ts页面添加属性
let dialog: MatDialog;
//导入模块
imports: [MatDialogModule]
providers: [
{
// I was expecting this will pass the desired value
provide: MAT_DIALOG_DATA,
useValue: model
},
beforeEach(() => {
fixture = TestBed.createComponent(AppsComponent);
dialog = TestBed.inject(MatDialog);//初始化
component = fixture.componentInstance;
el = fixture.debugElement;
fixture.detectChanges();
});
完整的测试过程
it('当 点击编辑按钮,应该可以弹出 编辑页面.当点击保存应该会调用 保存接口,随后将会', () => {
//设置测试数据
component.dataSource = tempArray;
//监听open事件
spyOn(dialog, "open").and.callThrough();
//刷新页面
fixture.detectChanges();
//获取编辑按钮
let editBtns = el.queryAll(By.css(".editBtn"));
//点击第一个
editBtns[0].nativeElement.click();
//打开了弹框
expect(dialog.open).toHaveBeenCalled();
//获取弹框内的组件
let currentDialog = dialog.getDialogById("dialog-app-detail")!;
//注册监听的事件
spyOn(currentDialog, "close").and.callThrough();
//判断获取到的对象是不是 AppDetailComponent
expect(currentDialog?.componentInstance).toBeInstanceOf(AppDetailComponent);
//点击这个按钮 cancelBtn 按钮的定义
currentDialog?.componentInstance?.cancelBtn.nativeElement.click();//点击取消按钮
expect(currentDialog.close).toHaveBeenCalled();
});
AppDetailComponent组件内 按钮的定义,这种需要为了测试添加代码,应该有别的方式可以获取到,我暂时还没找到。
@ViewChild('cancelBtn') cancelBtn?: MatButton;
更新: 也可以通过这种手段,获取组件内标签。 非常好用。
let button = document.getElementsByClassName("cancelBtn");
expect(button).withContext("通过DOC获取标签").not.toBeNull();
expect(button[0]).toBeInstanceOf(HTMLButtonElement);
(button[0] as HTMLButtonElement).click();