Error while performing angular Unit testing with SpyOn document

829 Views Asked by At

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.

2

There are 2 best solutions below

0
Anand Bhushan On BEST ANSWER

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();
   });
0
Paul On

What are you trying to test in your code above? The slugName, or that a service has been called?

Either way, there are better ways of doing that.

Testing if slugName has been set as id

Try using your fixture to get the html-object:

i.e, componentFixture.debugElement.query('#slugName').nativeElement.id

Spy on your service to see if the "getData" component has been subscribed to.

TestBed.inject(UsageService)

I believe get is deprecated.