Testing: spyOn Helper class in angular

1432 views javascript
-3

Is it possible to spyOn helper class? In the below code, StatefulPatternService.init() is calling a WebSocketHelper.

I like to spyOn WebSocketHelper and mock the subscribeFn

 export class WebSocketHelper{
  
  private url: string;
  
  constructor(url){
    this.url = url;
    init();
  }
  
  init(){
    // init websocket & other login
  }
}


@Injectable({
  providedIn: 'root'
})
export class StatefulPatternService {
  constructor(){}
  
  private callback(_data){ }
  
  init(){
  
    let wsHelper = new WebSocketHelper('/subscribe/topic'); // <-- How to spyOn???
    wsHelper.subscribeFn = this.callback;
    // ...    
  }
}

If spyOn won't be possible, how it can be written so that test can be covered.

answered question

1 Answer

3

Try this:

export class WebSocketHelper{
  
  public subject: Subject<any> = new Subject<any>();
  
  private url: string;
  
  constructor(url){
    this.url = url;
    init();
  }
  
  init(){
    // init websocket & other login
    this.subject.next('something');
  }
}


@Injectable({
  providedIn: 'root'
})
export class StatefulPatternService {
  constructor(){}
  
  private callback(_data){ }
  
  init(){
  
    let wsHelper = new WebSocketHelper('/subscribe/topic'); // <-- How to spyOn???
    wsHelper.subject.subscribe(this.callback);
    // ...    
  }
}

posted this

Have an answer?

JD

Please login first before posting an answer.