I want to test my service in angular with karma and jasmine, I begin with unit tests and I don't found any solution for my case or because I don't know how I can fix the issue. I always have a problem with my fields which are often undefined I don't understand why. If you can explain me what is the real problem It will be very nice to be able to progress in my tests.
My service
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class CanvasElementService {
public canvasContainer: HTMLDivElement;
private scaleProperty: string = 'scale(1)';
public updateScale(scale: number) {
this.scaleProperty = `scale(${scale})`;
this.update();
}
public update(): void {
this.canvasContainer.style.transform = this.scaleProperty;
}
}
And my test
import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { CanvasElementService } from './canvas-element.service';
fdescribe('CanvasElementService', () => {
let service: CanvasElementService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(CanvasElementService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
describe("updateScale", () => {
it("updatescale 2", () => {
let scale = 3;
spyOn(service, 'update').and.callThrough();
service.updateScale(scale);
expect(service['scaleProperty']).toBe('scale(3)');
});
});
});
After run test I got :
thanks for help If you have any idea to fix it.
Im not quite sure how to access a htmlElement in services. I think its only meant to be used by components (which have access to elements via @ViewChild() decorator).
You can try to achieve it by injecting your document into the service constructor and search for your element. Something like this:
constructor(@Inject(DOCUMENT) private document: HTMLDocument) {}
But its really not recommend to use services to access your dom. Use components or directives for it.
https://medium.com/@smarth55/angular-bad-practices-patterns-service-that-touch-the-dom-57ea978dca92