我正在创建一个不使用 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/