要编写Angular 7的matdialog open方法的单元测试案例,可以按照以下步骤进行:
确保你已经安装了Angular CLI,并创建了一个新的Angular项目。
在你的组件中,使用mat-dialog组件,并在需要测试的方法中调用open方法。
import { MatDialog } from '@angular/material/dialog';
@Component({
selector: 'app-your-component',
template: '',
})
export class YourComponent {
constructor(private dialog: MatDialog) {}
openDialog() {
this.dialog.open(YourDialogComponent);
}
}
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MatDialog } from '@angular/material/dialog';
import { YourComponent } from './your-component.component';
describe('YourComponent', () => {
let component: YourComponent;
let fixture: ComponentFixture;
let dialog: MatDialog;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [YourComponent],
providers: [MatDialog],
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(YourComponent);
component = fixture.componentInstance;
dialog = TestBed.inject(MatDialog);
fixture.detectChanges();
});
it('should open dialog when openDialog is called', () => {
spyOn(dialog, 'open');
component.openDialog();
expect(dialog.open).toHaveBeenCalled();
});
});
在这个示例中,我们首先在beforeEach块中配置测试环境。然后,我们创建了组件实例和MatDialog的mock实例。使用spyOn函数来监视dialog.open方法是否被调用。最后,在测试用例中调用openDialog方法并断言dialog.open方法已被调用。
注意:在以上示例中,我们使用了spyOn函数来监视dialog.open方法的调用。这是一种常见的测试技巧,可以用来验证方法是否被调用,以及调用时传递的参数等。