Testing out the following code:
constructor(drawingService: DrawingService) {
super(drawingService);
//...
}
private writeOnCanvas(): void {
this.drawingService.clearCanvas(this.drawingService.previewCtx);
this.drawingService.baseCtx.fillStyle = 'red';
this.drawingService.baseCtx.font = 'arial 20px';
this.drawingService.baseCtx.textAlign = 'center';
this.drawingService.baseCtx.fillText("hello",0, 0);
}
Introducing the DrawingService:
export class DrawingService {
baseCtx: CanvasRenderingContext2D;
previewCtx: CanvasRenderingContext2D;
cursorCtx: CanvasRenderingContext2D;
canvas: HTMLCanvasElement;
previewCanvas: HTMLCanvasElement;
clearCanvas(context: CanvasRenderingContext2D): void {
//do something
}
This is my .spec file:
fdescribe('TextService', () => {
let service: TextService;
let drawingServiceSpy: jasmine.SpyObj<DrawingService>;
// const drawingServiceMock = {
// clearCanvas: jasmine.createSpy('clearCanvas'),
// baseCtx : CanvasRenderingContext2D,
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{ provide: DrawingService, useValue: drawingServiceSpy },
]
});
drawingServiceSpy = jasmine.createSpyObj('DrawingService',['clearCanvas']);
service = TestBed.inject(TextService);
});
it('shoud write on baseCtx', () => {
const ctx = CanvasType.baseCtx;
service['drawingService'].baseCtx.fillStyle = 'red';
service['drawingService'].baseCtx.font = 'Bold 10px Arial';
service['drawingService'].baseCtx.textAlign = 'center' as CanvasTextAlign;
service['writeOnCanvas'](ctx);
expect(drawingServiceSpy.clearCanvas).toHaveBeenCalled();
expect(drawingServiceSpy.baseCtx.fillText).toHaveBeenCalled();
});
The error message received is:
Cannot set property 'fillStyle' of undefined' error.
The issue may be related to:
{
provide: DrawingService,
useValue: drawingServiceSpy
}
Attempts were made using a mockClass but encountered errors...