I am trying to do the unit testing for component, I mocked the data and expecting some result but getting an error, below is my unit test.
it('should call getData method ', () => {
const usageService = TestBed.get(UsageService);
component.slug = 'slugName';
spyOn(document, 'getElementById').and.returnValue("slugName");
component.ngOnInit();
expect(usageService.getData).toHaveBeenCalled();
});
In above I am getting an error at line spyOn(document, 'getElementById').and.returnValue("slugName");
Error is:
Argument of type "slugName" is not assignable to parameter of type 'HTMLElement'.
This issue comes after upgrading jasmine version from 2.8 to 3.5.10
I don't know what's wrong in this code, why previously it was working fine and now after upgrading it won't work.
please help me to resolve the issue.
You're getting a valid and self descriptive error, return type of getElementById is HTMLElement
and you're returning string
.
We would be in a better position to help you if you could paste the ngOnInit code which you're trying to test.
Nevertheless, you can take help from below code.
it('should call getData method ', () => {
const usageService = TestBed.get(UsageService);
spyOn(usageService, 'getData'); // toHaveBeenCalled works on mocked method
component.slug = 'slugName';
const htmlEl = document.createElement('div'); // you can create the element which is there in your component.
spyOn(document, 'getElementById').and.returnValue(htmlEl); // return created element on the previous line.
component.ngOnInit();
expect(usageService.getData).toHaveBeenCalled();
});