I'm trying to modify and instance-object's behaviour for testing. If you need to know exactly what I'm trying to achive, it's this:
const fakeWebSocket$$: WebSocketSubject<any> = new Subject<any>() as WebSocketSubject<any>;
fakeWebSocket$$.multiplex = (x: any, y: any, filterFn: (z: any) => boolean) =>
fakeWebSocket$$.pipe(filter(filterFn));
which is attaching a fake multiplex
-method to an RxJS-Subject
to be able to emulate a WebSocketSubject
.
This works fine, but notice how I have to refer to the fakeWebSocket$$
twice:
// simplified for readability
fakeWebSocket$$.multiplex = (x, y, filterFn) => fakeWebSocket$$.pipe(filter(filterFn));
I'd hope there is a way to replace the second explicit call to fakeWebSocket$$
with this
, somehow?
CodePudding user response:
To be able to use this
, you have to rewrite the arrow function to a normal function
function:
fakeWebSocket$$.multiplex = function (x, y, filterFn) {
return this.pipe(filter(filterFn));
};
This usage is not documented, but it should work.
The documentation however is written in such a way that suggests creating a derived class to override multiplex()
, rather than assigning a new value directly to the instance:
class FakeSubject<T> extends WebSocketSubject<T> {
override multiplex(
subMsg: () => any,
unsubMsg: () => any,
messageFilter: (value: T) => boolean
) {
return this.pipe(filter(messageFilter));
}
}
const fakeWebSocket$$ = new FakeSubject();