TypeError: cannot set properties of null (setting 'innerHtml')
I have created a simple angular service that initializes the inner html of a div tag in the main component of my angular project and is called in multiple components. When I run my tests I get the above karma error. I assume this is because the component is not created in the service.spec.ts file. I have checked and the class is defined in the main html file.
service.ts function:
onCLick(value: string): void {
document.querySelector('div.class').innerHtml = value;
}
service.spec.ts:
descirbe('ClickedService', () => {
let service: ClickedService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(ClickedService);
});
to("#onClick should add to innerHtml", () => {
service.onClick('test value'); // error is here
});
});
CodePudding user response:
welcome to the StackOverflow. To be honest, I wouldn't bother with fixing this unit test, because it looks like your approach to update the value is completely incorrect in the first place.
In Angular world, Service should provide you with values, and it can obtain them either from server via HTTP, or as a result of internal calculation. Then it's up to a Component, which is using this service, to deal with the value and display it if needed.
The reason why your test is not working is, that while creating the TestBed for the service, HTML is not expected and you are not providing any. Your querySelector
within the service can't find the div you are looking for and you can't set innerHtml
value to null.
If you really want to make this value and this logic available within the application, move it to a standalone component. You can then add it wherever you want, it will wrap the logic and it will prevent the repetition of the code. Don't use service with JS queries to update HTML, this will only lead to serious issues in the future.
Check this article about binding in angular to get better idea of what to do.