简体   繁体   中英

Error while performing angular Unit testing with SpyOn document

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

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:

ie, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM