问题描述
我收到一个预期的Spy错误,但在我的angular 10测试中未定义.我正在使用茉莉花和业力.我已经将服务SpreadsheetService嘲笑为mockSpreadSheetService.我正在调用它的方法.我不明白为什么它会期待间谍.
I am getting an error expected Spy but got undefined in my angular 10 test. I am using Jasmine and Karma. I have mocked the service SpreadsheetService as mockSpreadSheetService. I am calling the its method. I fail to understand why its expecting a spy.
我想到的一个可能原因是在运行测试之前创建了mockSpreadSheetService,并且我们正在调用component.ngOnit,这可能会重新创建组件实例.我试图在component.ngOnit之后显式创建模拟服务,但仍然无法正常工作.
One possible reason i could think of is that mockSpreadSheetService gets created before running the test and we are calling component.ngOnit which possible recreates the component instance. I tried to explicitly create the mockservice after component.ngOnit but it still didnt work.
我的问题理想情况下,我们应该在模拟对象上进行测试.为什么需要间谍.
My question Ideally we should be testing on the mock object. Why is spy needed.
expect(mockSpreadSheetService.loadXML).toHaveBeenCalled();
TestComponent
TestComponent
let component: SpreadsheetComponent;
let fixture: ComponentFixture<SpreadsheetComponent>;
let mockSpreadSheetService;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
declarations: [SpreadsheetComponent],
providers: [{SpreadsheetService, useFactory: () => mockSpreadSheetService.Object}]
})
.compileComponents();
}));
beforeEach(() => {
mockSpreadSheetService = new Mock<SpreadsheetService>({
loadXML: () => of(xmlData)
});
fixture = TestBed.createComponent(SpreadsheetComponent);
component = fixture.componentInstance;
//fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should call loadXML when ngOnInit is called', fakeAsync(() => {
// spyOn(component.spreadsheetService, 'loadXML');
component.ngOnInit();
tick();
expect(mockSpreadSheetService.loadXML).toHaveBeenCalled();
}));
});
主要组成部分
ngOnInit(): void {
this.spreadsheetService.loadXML().subscribe((data) => {
this.parseXML(data)
.then((data) => {
console.log('data is ' , data);
this.xmlItems = data;
});
});
}
推荐答案
间谍未正确创建.
这是它的外观:
let component: SpreadsheetComponent;
let fixture: ComponentFixture<SpreadsheetComponent>;
let mockSpreadSheetService;
beforeEach(async(() => {
mockSpreadSheetService = jasmine.createSpyObj(['loadXML']);
mockSpreadSheetService.loadXML.and.returnValue(of());
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
declarations: [SpreadsheetComponent],
providers: { provide: SpreadsheetService, useValue: mockSpreadSheetService }
});
fixture = TestBed.createComponent(SpreadsheetComponent);
component = fixture.componentInstance;
fixture.detectChanges();
}));
it('should create', () => {
expect(component).toBeTruthy();
});
it('should call loadXML when ngOnInit is called', () => {
component.ngOnInit();
expect(mockSpreadSheetService.loadXML).toHaveBeenCalled();
});
});
这篇关于错误:< toHaveBeenCalled> :可能是间谍,但未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!