我正在创建一个没有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
?
答案 0 :(得分:2)
OP提到答案是使用间谍。
fakeSocket = new Subject<any>(); spyOn(Observable, 'webSocket').and.returnValue(fakeSocket);