我有一个使用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
在这种情况下,有关操作员情况的任何线索?
我在用着 :
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
(try typeof factory
)of()
认为您正在传递调度程序。Substitute.for
实际上,返回时Proxy
会混淆RxJS检查。因此,出于这个原因,它从不发出任何东西。
无论如何,您可以这样做:
from([factory]).subscribe((f) => console.log("got it"));
很好抓住!谢谢。因此,这意味着在RxJS 8之前,我还必须避免在生产代码中使用“ of”,因为模拟参数在单元测试期间将不起作用。除非还有其他绕过此方法的方法?
of()
可以与包括函数之类的任何值一起正常工作,of(() => {})
但这是一个特殊的用例,其中它不知道如何处理Proxy
对象。如果您将嘲笑对象用于,of()
那么恐怕别无选择,of()
只能立即使用。明天我将在RxJS的GitHub页面上提交问题。您可能不是唯一遇到此问题的人。