jas*_*sie 7 dialog jasmine typescript angular-material angular
我从 Karma Jasmine 收到以下错误:
TypeError: Cannot read property 'afterClosed' of undefined
我真诚地搜索,但在 Stack Overflow 或其他来源中找不到解决方案。
这就是我MatDialog在组件中打开的方式:(
如文档所示)
constructor(public dialog: MatDialog) {}
public openDialog(): void {
const dialogReference: MatDialogRef<any, any> = this.dialog.open(myDialogComponent, {
width: '1728px'
});
dialogReference.afterClosed().subscribe((result) => {
});
}
Run Code Online (Sandbox Code Playgroud)
这是我的单元测试配置:
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
myRequestComponent
],
imports: [
MatDialogModule,
ReactiveFormsModule
],
providers: [
{ provide: MatDialog, useValue: {} },
],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(myRequestComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
Run Code Online (Sandbox Code Playgroud)
这是我的单元测试:
it('openDialog() should open a dialog', () => {
spyOn(component.dialog, 'open');
component.openDialog();
expect(component.dialog.open).toHaveBeenCalled();
});
Run Code Online (Sandbox Code Playgroud)
我是否必须模拟 MatDialog 或 MatDialogReference?
让我们逐步解决您的问题。
首先,通过注册
providers: [{ provide: MatDialog, useValue: {} }],
Run Code Online (Sandbox Code Playgroud)
您的测试平台将在MatDialog需要解决时注入一个没有行为的对象(例如实例方法/成员)。
这并不是真正必要的,因为您正在将 导入MatDialogModule到您的测试台中,因此MatDialog可以毫无问题地解决实例。但让我们坚持你的方法。 此解决方案将要求您删除该行。
其次,通过做:
spyOn(component.dialog, 'open')
Run Code Online (Sandbox Code Playgroud)
您正在为引用的对象中的实例方法安装代理。在这种情况下,您之前注册的空对象。opencomponent.dialog
尽管该对象没有这样的成员,但 jasmine 会在其位置动态添加代理。这就是为什么您看不到像this.dialog.open is not a function.
最后,无论何时与之交互,代理都会记录有关这些交互的信息并将呼叫重定向到原始open成员。因为没有原始实现,所以会用一个没有返回的函数来代替它,这最终会触发accessing foo of undefined.
TL; 博士;
删除{ provide: MatDialog, useValue: {} }并使用以下内容来模拟所需的MatDialogRef实例:
import { EMPTY} from 'rxjs';
it('openDialog() should open a dialog', () => {
const openDialogSpy = spyOn(component.dialog, 'open')
.and
.returnValue({afterClosed: () => EMPTY});
component.openDialog();
expect(openDialogSpy).toHaveBeenCalled();
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7518 次 |
| 最近记录: |