如何为单元测试模拟RxJs可观察的Websocket [英] How to mock RxJs Observable Websocket for Unit Tests

查看:84
本文介绍了如何为单元测试模拟RxJs可观察的Websocket的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular 4和RxJs创建一个Web应用程序.在我的代码的一部分中,我使用以下代码创建一个Websocket: Observable.websocket(url); 函数.

I am creating a web app unsing Angular 4 and RxJs. In one part of my code I am creating a websocket using: Observable.websocket(url); function.

这是我的代码:

  /**
   * Tries to open a websocket connection to a given URL.
   * @param url
   * @param subscription Previous subscription to this socket (it may be necessary to close it before proceeding)
   * @returns an object containing the subscription and the websocket subject.
   */
  private openConnection(url: string, subscription: Subscription): { socket$: WebSocketSubject<any>, subscription: Subscription } {
    const socket$ = Observable.webSocket<string>(url);

    // Make sure we unsubscribe from the previous socket if necessary.
    if (subscription) {
      subscription.unsubscribe();
    }

    // Subscribe the recently created socket. Note: this must be done otherwise the socket won't work.
    const newSubscription = socket$.subscribe(
      (msg: string) => this.handleIncomingMessages(msg),
      (error: Error) => this.handleErrors(error),
      () => this.handleComplete());

    return { socket$: socket$, subscription: newSubscription };
  }

我接下来要做的是为我的websocket创建一个单元测试.但是,为了做到这一点,我需要创建一个模拟websocket,以便我可以自由地发送和接收来自它的消息.

The next thing that I would like to do, is to create an unit test for my websocket. However in order to do this I would need to create a mock websocket so that I can freely send and receive messages from it.

有人知道怎么做吗?可以为此使用Angular MockBackend 吗?

Does anyone knows how to do this? Is it possible to use the Angular MockBackend for this?

推荐答案

正如OP所述,答案是使用间谍.

As OP mentioned the answer was to use spies.

fakeSocket = new Subject<any>(); spyOn(Observable, 'webSocket').and.returnValue(fakeSocket);

这篇关于如何为单元测试模拟RxJs可观察的Websocket的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆