javascript - 如何模拟 RxJs Observable Websocket 进行单元测试

标签 javascript angular unit-testing rxjs

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

这是我的代码:

  /**
   * 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,以便我可以自由地从中发送和接收消息。

有人知道该怎么做吗?是否可以使用 Angular MockBackend 来实现此目的?

最佳答案

正如OP提到的,答案是使用 spy 。

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

关于javascript - 如何模拟 RxJs Observable Websocket 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48584094/

相关文章:

javascript - Angular 8 : (keyup. 输入)不触发只读 html 输入

javascript - Web Components 如何减轻 JavaScript 库膨胀?

angular - 为什么我不能直接设置 Angular Material 步进器元素的样式?

unit-testing - 无法加载文件或程序集“Moq,4.2.1502.911”或其依赖项之一

python - 如何清除 memoize 缓存?

javascript - 为什么节点和监听器没有以一致的方式正确清理?

angular - 如何在 Electron 中将 livereload 与 Webpack 一起使用?

javascript - 我们可以将 System.import 或 import() 函数用于任何 Javascript 文件或仅针对单个模块特定的 js 吗?

ruby - 在 rspec 中测试递归 IO 提示

javascript - Highcharts 具有多个区域范围和线系列的鼠标跟踪行为