Angular Jasmine测试:预期是间谍,但未定义



我在角度和书写测试中使用材料对话框来测试对话框的关闭我得到了错误预期的间谍,但得到了未定义。测试中出现错误fit("应该调用函数关闭对话框">

describe('XYZDetailsComponent', () => {
let component: XYZDetailsComponent;
let fixture: ComponentFixture<XYZDetailsComponent>;
const data = {
ip: '1.1.1.1',
name: 'test'
}
const setupComponent = () => {
fixture = TestBed.createComponent(XYZDetailsComponent);
component = fixture.componentInstance;
fixture.detectChanges();
};
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule, MatDialogModule ],
declarations: [XYZDetailsComponent],
providers: [
{ provide: MatDialogRef, useFactory: () => jasmine.createSpyObj('MatDialogRef', ['close', 'afterClosed']) },
{provide: MAT_DIALOG_DATA, useValue: data},
]
})
.compileComponents();
});
it('should create', () => {
setupComponent();
expect(component).toBeTruthy();
});
fit('should call the function to close the dialog', () => {
setupComponent();
component.onNoClick();
expect(component.dialogRef.close()).toHaveBeenCalled();
});
});

我认为您需要从外部(从测试(而不是从组件获取MatDialogRef的句柄。

试试这个,请用你的类型替换anys

describe('XYZDetailsComponent', () => {
let component: XYZDetailsComponent;
let fixture: ComponentFixture<XYZDetailsComponent>;
// add this line
let mockDialogRef: jasmine.SpyObj<any>;
const data = {
ip: '1.1.1.1',
name: 'test'
}
const setupComponent = () => {
fixture = TestBed.createComponent(XYZDetailsComponent);
component = fixture.componentInstance;
fixture.detectChanges();
};
beforeEach(() => {
// assign the variable to spy object before each test
// This ensures we get fresh spies for each test
mockDialogRef = jasmine.createSpyObj('MatDialogRef', ['close', 'afterClosed']);
TestBed.configureTestingModule({
imports: [HttpClientTestingModule, MatDialogModule ],
declarations: [XYZDetailsComponent],
providers: [
// modify this line
{ provide: MatDialogRef, useValue: mockDialogRef ,
{provide: MAT_DIALOG_DATA, useValue: data},
]
})
.compileComponents();
});
it('should create', () => {
setupComponent();
expect(component).toBeTruthy();
});
fit('should call the function to close the dialog', () => {
setupComponent();
component.onNoClick();
// alter this line
expect(mockDialogRef.close).toHaveBeenCalled();
});
});

最新更新