0

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!

Kerwen
  • 516
  • 5
  • 22

2 Answers2

1

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.

  1. The simplest way is to change signature to protected.

So private processConnect() turns into processConnect() (we can write it without the protected signature because it's by default)

  1. You can use array access.

So if you have a private method like this

export class SocketService {
  ....
  private processConnect() {
    ...
  }
}

You can access it using array access

socketService['processConnect']
0
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();
}
Kerwen
  • 516
  • 5
  • 22