我有一个简单的单元测试,使用 Substitute.js (还尝试了 TypeMoq 模拟,我将描述的行为是相同的)。
在此测试中,我尝试了最简单的方法,使用 of
运算符发出模拟对象。如果没有任何其他运算符,则永远不会调用订阅回调。示例:
import {Arg, Substitute, SubstituteOf} from "@fluffy-spoon/substitute";
import "reflect-metadata";
import {Observable, of} from "rxjs";
const factory = Substitute.for<MessageFactory>();
of(factory).subscribe((f) => console.log("got it"));
控制台日志永远不会被调用。
现在,如果我不使用运算符而只是创建一个可观察对象,则日志将正常工作。示例:
import {Arg, Substitute, SubstituteOf} from "@fluffy-spoon/substitute";
import "reflect-metadata";
import {Observable, of} from "rxjs";
const factory = Substitute.for<MessageFactory>();
new Observable((subscriber) => {
subscriber.next(factory);
subscriber.complete();
}).subscribe((f) => console.log("got it"));
在这种情况下,有关于 of
运算符发生了什么的任何线索吗?
我正在使用:
- rxjs:6.5.4
- typescript :3.5.3
- Node :v10.18.1
最佳答案
of()
方法有一个特殊的用例,您将 RxJS Scheduler
的实例作为最后一个参数传递。 (此用例已弃用,并将在 RxJS 8 中删除)。
https://github.com/ReactiveX/rxjs/blob/master/src/internal/observable/of.ts#L9
例如,您可以执行以下操作:
of(1, 2, 3, asyncScheduler)
自 Substitute.for<MessageFactory>()
返回 function
(尝试typeof factory
)of()
认为您正在通过调度程序。 Substitute.for
事实上返回 Proxy
在令人困惑的引擎盖下RxJS check 。因此,由于这个原因,它永远不会发出任何东西。
无论如何,你可以这样做:
from([factory]).subscribe((f) => console.log("got it"));
关于node.js - 使用代理时,运算符的 Rxjs 不发出值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60020865/