我正在尝试测试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$;
}
这总是返回未定义的。我的自动化测试也会失败。
it('should confirm a record exists in storage', fakeAsync( () => {
let Exists:boolean;
const Status$:Subject<boolean> = ServiceUnderTest.Exists('Good'); // This exists in Firebase
Status$.subscribe( (Result:boolean) => {
Exists = Result;
});
flushMicrotasks();
Status$.unsubscribe();
expect(Exists).toBeTrue();
}));
我在Firebase中可以访问/ Testing / Good,这是一个具有Key_和Name结构的对象。
来自package.json的模块
"@angular/fire": "^5.4.2",
"firebase": "^7.9.3",
但是,如果我只是尝试不直接返回AngularFire而返回结果,则这些测试有效。
public Exists(Id:string):BehaviorSubject<boolean> {
const Status:BehaviorSubject<boolean | undefined> = new BehaviorSubject<boolean | undefined>(undefined);
Status.next(true);
return Status;
}
next
来自RecordExists
时,您必须在主题上调用.valueChanges()
,>]
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) { Status$.next(true); } else { Status$.next(false); } }) ; return Status$;
您的代码在测试和简单示例中的行为方式不同,因为两者均以同步方式调用此
.valueChanges()
,因此在.next()
之后调用subscribe
。在现实生活中,valueChanges是异步的,因此在subscribe
之前调用next
。
====================编辑=====================>
要与真实数据库连接,您必须将测试修改为异步(因为连接是异步的:
it('should confirm a record exists in storage',((done) => {
Status$.subscribe( (Result:boolean) => {
expect(Exists).toBeTrue();
done()
});
d}))