Kerwen
Kerwen

Reputation: 552

How to test the method of a private property is called in Angular

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

Answers (2)

Kerwen
Kerwen

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

Dmytro Demianenko
Dmytro Demianenko

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.

  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']

Upvotes: 1

Related Questions