使用RxJS主题对存在的对象进行角度射击测试

使用RxJS主题对存在的对象进行角度射击测试,rxjs,observable,angularfire,Rxjs,Observable,Angularfire,我试图测试我的AngularFire表中是否存在一个对象。我在返回主题以检测文件是否存在时遇到问题 /** * Check if the Id exists in storage * @param Id string | number Key value to check * @returns Subject<boolean> */ public Exists(Id:string):Subject<boolean> { const Status$:Subj

我试图测试我的AngularFire表中是否存在一个对象。我在返回主题以检测文件是否存在时遇到问题

/**
 * Check if the Id exists in storage
 * @param Id string | number Key value to check
 * @returns Subject<boolean>
 */
public Exists(Id:string):Subject<boolean> {
    const Status$:Subject<boolean> = new Subject<boolean>();

    let RecordExists:boolean = false;
    this.AfDb_.object<T>(`_Testing_/${Id}`).valueChanges()
        .subscribe( (OneRecord:T) => {
            if (OneRecord.Key_ !== undefined && OneRecord.Key_ !== null && OneRecord.Key_.length > 0) {
                RecordExists = true;
            }
        })
    ;
    Status$.next(RecordExists);
    return Status$;
}
然而,如果我只是尝试返回一个结果而不直接去AngularFire,这些测试就可以工作

public Exists(Id:string):BehaviorSubject<boolean> {
    const Status:BehaviorSubject<boolean | undefined> = new BehaviorSubject<boolean | undefined>(undefined);

    Status.next(true);
    return Status;
}
public存在(Id:string):行为主体{
常量状态:BehaviorSubject=新的BehaviorSubject(未定义);
状态。下一个(true);
返回状态;
}

如果
记录存在
来自
.valueChanges()
时,您必须调用
下一步
,以了解主题,例如:

let RecordExists:boolean=false;
this.AfDb_.object(`u Testing\/${Id}`).valueChanges()
.订阅((OneRecord:T)=>{
如果(OneRecord.Key!==未定义&&OneRecord.Key!==空&&OneRecord.Key!==长度>0){
状态$.next(true);
}否则{
状态$.next(false);
}
})
;
返回状态$;
在测试和简单示例中,您的代码以不同的方式运行,因为两者都以同步方式调用this
.valueChanges()
,所以
.next()
subscribe
之后调用。在现实生活中,valueChanges是异步的,因此在
next
之前调用
subscribe

============================编辑=====================

要连接真实数据库,您必须将测试修改为异步(因为连接是异步的:

it('应确认存储器中存在记录',((完成)=>{
状态$.subscribe((结果:布尔值)=>{
expect(存在)。toBeTrue();
完成()
});
d} ))

即使我正在设置在subscribe块之外声明的变量,我也需要它。RecordExists是在调用AngularFire之前定义的。在subscribe块中设置它,也是一样吗?Subject不会发出任何东西,因为变量被覆盖,所以每次都必须调用
。下一步
方法。我的尽管测试仍然失败,表明undefined不是真的。在测试中设置为“Exists”的变量似乎也没有它的值。但是,这是我试图验证的最终结果。可能我不理解每个时间方面,因为这只是一个对象,而不是一个列表。你确定
这个.AfDb_.object(
\u测试<${Id}
).valueChanges()
在测试中被模拟了吗?我并不是真的在模拟这个。我是用一个真实的数据库来尝试它,这是一个数据存在的路径。我是在尝试真实的数据库,以确保我的测试在没有模拟的情况下工作,以消除一个级别的可能错误。我应该补充一点,在服务功能中执行console.log将显示数据存在。
"@angular/fire": "^5.4.2",
"firebase": "^7.9.3",
public Exists(Id:string):BehaviorSubject<boolean> {
    const Status:BehaviorSubject<boolean | undefined> = new BehaviorSubject<boolean | undefined>(undefined);

    Status.next(true);
    return Status;
}