Failure to simulate the return value of getSocketIOConnector
method caused the error. It is crucial to remember to execute fixture.detectChanges();
after mocking in order to activate the ngOnInit
method of the component.
Take a look at this functional demonstration utilizing angular
version 11+:
ondemand.component.ts
:
import { Component, OnInit } from '@angular/core';
import { SocketService } from './socket.service';
@Component({})
export class OndemandComponent implements OnInit {
socket: SocketService;
data = {
product: 'real product',
};
connectionMsg: string;
constructor(private socketService: SocketService) {}
ngOnInit() {
this.socket = this.socketService.getSocketIOConnector(this.data.product);
this.socket.on('connected', (message: string) => {
this.connectionMsg = message;
});
}
}
socket.service.ts
:
import { Injectable } from '@angular/core';
@Injectable()
export class SocketService {
getSocketIOConnector(params) {
return this;
}
on(event, listener) {}
}
ondemand.component.spec.ts
:
import { ComponentFixture, inject, TestBed } from '@angular/core/testing';
import { OndemandComponent } from './ondemand.component';
import { SocketService } from './socket.service';
fdescribe('65302152', () => {
let fixture: ComponentFixture<OndemandComponent>;
let component: OndemandComponent;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [OndemandComponent],
providers: [SocketService],
}).compileComponents();
fixture = TestBed.createComponent(OndemandComponent);
component = fixture.componentInstance;
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should check socket service', inject(
[SocketService],
(socketioService: SocketService) => {
const connectorSpy = jasmine.createSpyObj('connector', ['on']);
connectorSpy.on.and.callFake((event, listener) => {
listener('fake message');
});
const getSocketIOConnectorSpy = spyOn(
socketioService,
'getSocketIOConnector'
).and.returnValue(connectorSpy);
// trigger ngOnInit of component
fixture.detectChanges();
expect(getSocketIOConnectorSpy).toHaveBeenCalledOnceWith('real product');
expect(connectorSpy.on).toHaveBeenCalledOnceWith(
'connected',
jasmine.any(Function)
);
}
));
});
unit test result:
https://i.sstatic.net/ULfWJ.png