Reputation: 552
I have a class which has a private property.
import {Socket} from 'socket.io-client';
export class SocketService {
private socket: Socket;
public initializeSocket() {
if(this.socket) { return; }
this.socket = // get a new Socket
this.socket.on('connect', () => this.processConnect() );
}
private processConnect() {
...
}
}
When write unit test for method initializeSocket()
, how to validate that the on
is called? Any suggestion would be appreciated!
Upvotes: 0
Views: 735
Reputation: 552
it('test socket on',()=>{
service['socket'] = tempSocket; // have to initialize it temply as spyOn need a object
spyOn(service['socket'], 'on');
service['socket'] = undefined;
service.initializeSocket();
expect(service['socket'].on).toHaveBeenCalled();
}
Upvotes: 0
Reputation: 387
You can't test private methods in a straight way.
There are 3 methods how to test it. It's written in this article Testing private methods in Typescript
I'm going to describe 2 of them.
So private processConnect()
turns into processConnect()
(we can write it without the protected signature because it's by default)
So if you have a private method like this
export class SocketService {
....
private processConnect() {
...
}
}
You can access it using array access
socketService['processConnect']
Upvotes: 1