簡體   English   中英

如何在 Jasmine 中模擬 rxjs webSocket?

[英]How to mock rxjs webSocket in Jasmine?

這是我的聊天服務:

import {webSocket, WebSocketSubject} from 'rxjs/webSocket';
import {delayWhen, retryWhen, take} from 'rxjs/operators';
import {timer} from 'rxjs';

...

export class ChatConnectionService {

  private readonly _connection: WebSocketSubject<any>;
  public readonly messages$: Observable<ChatInboundMessage>;

  constructor() {
    this._connection = this.getConnection();
    this.messages$ = this._connection.asObservable();
  }

  private getConnection(): WebSocketSubject<any> {
    return webSocket(`.../chat`);
  }

}

到目前為止,這是我嘗試過的:

import * as rxJsWebSocket from 'rxjs/webSocket';

describe('ChatConnectionService', () => {
  let service: ChatConnectionService;

  const subject = new Subject();
  let webSocketSpy;

  beforeEach(() => {   
    webSocketSpy = spyOnProperty(rxJsWebSocket, 'webSocket', 'get').and.returnValue(<any>subject);

    service = new ChatConnectionService();
  });

  it('should create a new connection when service instantiated', () => {
    expect(webSocketSpy).toHaveBeenCalledTimes(1);
  });
});

但它給了我以下錯誤:

 Error: <spyOnProperty> : webSocket is not declared configurable

如何用 Subject 替換webSocket以便我可以測試它? RxJs:6.5.5

似乎沒有好的解決方案,這里有一個關於fromEvent運算符的類似主題: Error: <spyOn>: fromEvent is not declared writable or has no setter

如果意圖是直接監視操作員,那么唯一可行的選擇似乎是目標ES5 ,我不認為這是一個解決方案,因為部署的ES6+可以減少包的大小。

我想最好的選擇可能是為webSocket運算符設置一個包裝器 function。 包裝器 function 已經可以被窺探。 在您的示例中,最簡單的方法是為getConnection() function 設置一個間諜,它負責返回連接實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM