我正在尝试对我的对话进行单元测试。我期望在操作后关闭dialogRef。但是我得到了错误: '失败:this.dialogRef.close不是函数 TypeError:this.dialogRef.close不是函数'
我尝试了嘲笑,但没有任何结果。
我正在尝试对我的对话进行单元测试。我期望在操作后关闭dialogRef。但是我得到了错误: '失败:this.dialogRef.close不是函数 TypeError:this.dialogRef.close不是函数'
我尝试了嘲笑,但没有任何结果。
有什么建议吗?
import {async, ComponentFixture, TestBed} from
'@angular/core/testing';
import {CloneDialogComponent} from "./cloneDialog.component";
import {MAT_DIALOG_DATA, MatDialogModule, MatDialogRef,
MatDialogTitle}
from '@angular/material/dialog';
import {BrowserAnimationsModule} from "@angular/platform-
browser/animations";
describe('CloneDialogComponent', () => {
let component: CloneDialogComponent;
let fixture: ComponentFixture<CloneDialogComponent>;
const dialogMock = {
close: () => { }
};
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
CloneDialogComponent
],
imports: [
MatDialogModule,
BrowserAnimationsModule
],
providers: [
{provide: MatDialogTitle, useValue: {}},
{provide: MatDialogRef, useValue: {dialogMock}},
{provide: MAT_DIALOG_DATA, useValue: []}]
});
fixture = TestBed.createComponent(CloneDialogComponent);
component = fixture.componentInstance;
}));
it('should be created', () => {
expect(component).toBeTruthy();
});
it('No calls onNoClick()', async(() => {
spyOn(component, 'onNoClick');
fixture.detectChanges();
const button =
fixture.debugElement.nativeElement.querySelector('#no');
button.click();
expect(component.onNoClick).toHaveBeenCalled();
}));
it('Yes calls onYesClick()', async(() => {
spyOn(component, 'onYesClick');
fixture.detectChanges();
const button =
fixture.debugElement.nativeElement.querySelector('#yes');
button.click();
expect(component.onYesClick).toHaveBeenCalled();
}));
it('dialog should be closed after onYesClick()', async(() => {
component.onYesClick();
expect(component.dialogRef.close).toHaveBeenCalled();
}));
it('dialog should be closed after onNoClick()', async(() => {
component.onNoClick();
expect(component.dialogRef.close).toHaveBeenCalled();
}));
});
import {Component, Inject} from '@angular/core';
import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material';
@Component({
templateUrl: './cloneDialog.component.html',
styleUrls: ['./cloneDialog.component.sass']
})
export class CloneDialogComponent {
constructor(
public dialogRef: MatDialogRef<CloneDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: any) {
}
onNoClick(): void {
this.dialogRef.close(false);
}
onYesClick(): void {
this.dialogRef.close(true);
}
}
答案 0 :(得分:5)
您不需要dialogMock
周围的括号:
{provide: MatDialogRef, useValue: dialogMock},
并更改测试以使用间谍来监视close
函数,然后检查它是否已被调用:
it('dialog should be closed after onYesClick()', () => {
let spy = spyOn(component.dialogRef, 'close').and.callThrough();
component.onYesClick();
expect(spy).toHaveBeenCalled();
});
it('dialog should be closed after onNoClick()', () => {
let spy = spyOn(component.dialogRef, 'close').and.callThrough();
component.onNoClick();
expect(spy).toHaveBeenCalled();
});
正在工作的堆叠闪电是here。