Hi I wrote an angular unit test for a method which throws an error when there is no data. But that test is failing with the message TypeError: Cannot read property 'subscribe' of undefined. I tried so many things but still it fails.
This is the method in ts file
searchLogs(pageSize:number, pageIndex){
let logs = this.logForm.value;
logs.PageSize = pagesize;
logs.PageIndex = pageIndex;
this.myService.searchLogs(logs).subscribe((result)=> {
let logResult = result;
if(logResult){
this.dataSource = new MatTableDataSource<LogElement>(logResult)}
},
err => {
let errorMgs = err && err.error && err.error.error && err.error.error.message
? 'discription': '+ err.error.error.message.replace(/"/g, "").substring(0,250)
: "Error occured!";
});
}
this is the test case i wrote in spec.ts file
it('should run #searchLogs() with error', async() =>
{
component.logForm = component.logForm || {};
component.logForm.value = {
PageSize: {},
PageIndex: {}
};
component.myService = component.myService || {};
const errorResponse = new HttpErrorResponse({
error:{error: {error: "error", message: "Error occured!"}},
status: 0,
statusText: "Unknow Error",
})
const errorResponse1 = new HttpErrorResponse({
error:{error: {error: "error", message: null}},
status: 0,
statusText: "Unknow Error",
})
mockMyService.searchLogs.and.returnValue(throwError(errorResponse));
component.searchLogs({},{});
expect(component.myService.searchLogs).toHaveBeenCalled();
expect(component.dataSource.data).toEqual([]);
mockMyService.searchLogs.and.returnValue(throwError(errorResponse1));
component.searchLogs({},{});
expect(component.myService.searchLogs).toHaveBeenCalled();
expect(component.dataSource.data).toEqual([]);
}
);
Any idea why this is failing? Appreciate if anyone can help me :)
This is how i defined mockMyService
describe('LogViewerComponent', () => {
let mockMyService;
beforeEach(() => {
mockMyService = jasmine.createSpyObj('MyService', ['searchLogs']);
TestBed.configureTestingModule({
imports:[FormsModule, ReactiveFormsModule],
declarations:[LogViewerComponent],
schemas:[CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA],
providers: [
{provide: MyService, useValue: mockMyService}
]
}).overrideComponent(LogViewerComponent, {
}). compileComponents();
fixture = TestBed.createComponent(LogViewerComponent);
component = fixture.debugElement.componentInstance;
});
afterEach(()=> {
component.ngOnDestroy = function(){};
fixture.destroy();
});
)};