I'm quite new to RxSwift and I trying to create some unit tests. In this case I want to test If the fetch objects from Realtime database Firebase is occurring correctly.
func getAllPosts() -> Observable<[PostItem]> {
ref = Database.database().reference()
return Observable.create { observer -> Disposable in
self.ref.child("Posts").observe(.value) { (snapshot) in
var postsList:[PostItem] = []
for child in snapshot.children {
let snap = child as! DataSnapshot
let postDict = snap.value as! [String: Any]
let postAux = PostItem(id: snap.ref.key ?? "", authorId: postDict["authorId"] as? String ?? "", name: postDict["name"] as? String ?? "", content: postDict["content"] as? String ?? "", createAt: postDict["createAt"] as? String ?? "")
postsList.append(postAux)
}
observer.onNext(postsList)
}
return Disposables.create {}
}
}
The problem is the return of firebase is async and the way i'm trying the test is being completed before the return.
func testFetchPosts() throws {
let newsAPIService = NewsAPIService()
let posts = newsAPIService.fetchNewsFromAPI()
XCTAssertNil(posts, "The posts is nil")
}
Obs: I tried to use XCTest expectation but I don't know if had implemented incorrectly or if it doesn't really work
Thank you!