I would like to test if my init function works as expected. There is an async call in the init within a Task {} block. How can I make my test wait for the result of the Task block?
class ViewModel: ObservableObject {
#Published private(set) var result: [Item]
init(fetching: RemoteFetching) {
self.result = []
Task {
do {
let result = try await fetching.fetch()
self.result = result // <- need to do something with #MainActor?
} catch {
print(error)
}
}
}
}
Test:
func testFetching() async {
let items = [Item(), Item()]
let fakeFetching = FakeFetching(returnValue: items)
let vm = ViewModel(fetching: FakeFetching())
XCTAssertEqual(vm.result, [])
// wait for fetching, but how?
XCTAssertEqual(vm.result, items])
}
I tried this, but setting the items, only happens after the XCTWaiter. The compiler warns that XCTWaiter cannot be called with await, because it isn't async.
func testFetching() async {
let items = [Item(), Item()]
let fakeFetching = FakeFetching(returnValue: items)
let expectation = XCTestExpectation()
let vm = ViewModel(fetching: FakeFetching())
XCTAssertEqual(vm.result, [])
vm.$items
.dropFirst()
.sink { value in
XCTAssertEqual(value, items)
expectation.fulfill()
}
.store(in: &cancellables)
let result = await XCTWaiter.wait(for: [expectation], timeout: 1)
XCTAssertEqual(result, .completed)
}
Expectation-and-wait is correct. You're just using it wrong.
You are way overthinking this. You don't need an async test method. You don't need to call fulfill yourself. You don't need a Combine chain. Simply use a predicate expectation to wait until vm.result is set.
Basically the rule is this: Testing an async method requires an async test method. But testing the asynchronous "result" of a method that happens to make an asynchronous call, like your init method, simply requires good old-fashioned expectation-and-wait test.
I'll give an example. Here's a reduced version of your code; the structure is essentially the same as what you're doing:
protocol Fetching {
func fetch() async -> String
}
class MyClass {
var result = ""
init(fetcher: Fetching) {
Task {
self.result = await fetcher.fetch()
}
}
}
Okay then, here's how to test it:
final class MockFetcher: Fetching {
func fetch() async -> String { "howdy" }
}
final class MyLibraryTests: XCTestCase {
let fetcher = MockFetcher()
func testMyClassInit() {
let subject = MyClass(fetcher: fetcher)
let expectation = XCTNSPredicateExpectation(
predicate: NSPredicate(block: { _, _ in
subject.result == "howdy"
}), object: nil
)
wait(for: [expectation], timeout: 2)
}
}
Extra for experts: A Bool predicate expectation is such a common thing to use, that it will be found useful to have on hand a convenience method that combines the expectation, the predicate, and the wait into a single package:
extension XCTestCase {
func wait(
_ condition: #escaping #autoclosure () -> (Bool),
timeout: TimeInterval = 10)
{
wait(for: [XCTNSPredicateExpectation(
predicate: NSPredicate(block: { _, _ in condition() }), object: nil
)], timeout: timeout)
}
}
The outcome is that, for example, the above test code can be reduced to this:
func testMyClassInit() {
let subject = MyClass(fetcher: fetcher)
wait(subject.result == "howdy")
}
Convenient indeed. In my own code, I often add an explicit assert, even when it is completely redundant, just to make it perfectly clear what I'm claiming my code does:
func testMyClassInit() {
let subject = MyClass(fetcher: fetcher)
wait(subject.result == "howdy")
XCTAssertEqual(subject.result, "howdy") // redundant but nice
}
Tnx to matt this is the correct way. No need for async in the test function and just using a predicate did the job.
func testFetching() {
let items = [Item(), Item()]
let fakeFetching = FakeFetching(returnValue: items)
let expectation = XCTestExpectation()
let vm = ViewModel(fetching: FakeFetching())
let pred = NSPredicate { _, _ in
vm.items == items
}
let expectation = XCTNSPredicateExpectation(predicate: pred, object: vm)
wait(for: [expectation], timeout: 1)
}
Slight variation on Matt's excellent answer. In my case, I've broken out his extension method into even more granular extensions for additional convenience.
Helper Framework
public typealias Predicate = () -> Bool
public extension NSPredicate {
convenience init(predicate: #escaping #autoclosure Predicate) {
self.init{ _, _ in predicate() }
}
}
public extension XCTNSPredicateExpectation {
convenience init(predicate: #escaping #autoclosure Predicate, object: Any) {
self.init(predicate: NSPredicate(predicate: predicate()), object: object)
}
convenience init(predicate: #escaping #autoclosure Predicate) {
self.init(predicate: NSPredicate(predicate: predicate()))
}
convenience init(predicate: NSPredicate) {
self.init(predicate: predicate, object: nil)
}
}
public extension XCTestCase {
func XCTWait(for condition: #escaping #autoclosure Predicate, timeout: TimeInterval = 10) {
let expectation = XCTNSPredicateExpectation(predicate: condition())
wait(for: [expectation], timeout: timeout)
}
}
With the above in place, the OP's code can be reduced to this...
Unit Test
func testFetching() {
let items = [Item(), Item()]
let fakeFetching = FakeFetching(returnValue: items)
let vm = ViewModel(fetching: FakeFetching())
XCTWait(for: vm.items == items, timeout: 1)
}
Notes on Naming
Above, I'm using a somewhat controversial name in calling my function XCTWait. This is because the XCT prefix should be considered reserved for Apple's XCTest framework. However, the decision to name it this way stems from the desire to improve its discoverability. By naming it as such, when a developer types XCT In their code editor, XCTWait is now presented as one of the offered auto-complete entries** making finding and using much more likely.
However, some purists may frown on this approach, citing if Apple ever added something named similar, this code may suddenly break/stop working (although unlikely unless the signatures also matched.)
As such, use such namings at your own discretion. Alternately, simply rename it to something you prefer/that meets your own naming standards.
(** Provided it is in the same project or in a library/package they've imported somewhere above)
I am trying to get the element of 2 observables produced asynchronously and pass them as parameters to a function once both are received.
However my map operator in my ViewModel below is not executed and the breakpoint just skips over it.
ViewModel.swift
init(api: ApiService) {
self.api = api
}
func getData1() -> Observable<Data1> {
return api.getData1()
}
func getData2() -> Observable<NewViewModel> {
return Observable.create { observer in
let disposable = Disposables.create()
self.api.getData2()
.map {
$0.arrayOfStuff.forEach { (stuff) in
let background = stuff.background
let newViewModel = NewViewModel( background: self.spotlightBackground)
observor.onNext(newViewModel)
}
return disposable
}
}
In my ViewController i am creating the Zip of the observables because newViewModel[getData2] may return later and i want to call the function when both observables emit a value
in my viewDidLoad() i setup zip by subscribing and adding observables
let zippy = Observable.zip(viewModel.getData1(), viewModel.getData2()).subscribe(onNext: { (data1, newViewModel) in
self.layoutSetUp(data1: data1, newViewModel: newViewModel)
})
zippy.disposed(by: disposeBag)
private func layoutSetUp(data1: Data1, newViewModel: NewViewModel) {
DispatchQueue.main.async {
self.view = SwiftUIHostingView(rootView: SwiftUIContentView(data1: data1, newViewModel: newViewModel))
}
}
This is not executing and no values are passed to function either and im not sure why
Your getData2 method never emits a value so neither will the zip. The code in the method is a bit too muddled for me to understand what you are trying to do so I can't tell you exactly what you need, but I can say that when you have an observable that nothing is subscribed to, then it will not emit a value.
This bit:
self.api.getData2()
.map {
$0.arrayOfStuff.forEach { (stuff) in
let background = stuff.background
let newViewModel = NewViewModel(background: self.spotlightBackground)
observor.onNext(newViewModel)
}
return disposable
}
Is an observable with no subscribers.
I have a function which is supposed to return an Observable. When I call the function for the first time, everything goes fine and I receive the result I expected, but for the second time that I want to make the same request with different parameters the function automatically returns the same response as before and it does not fire the requests at all. There are multiple requests nested because each new depends on the results of the previous.
It looks something like this:
func request1() -> Observable<String> {
return RxAlamofire
.requestString(.get, url)
.map { (response, html) -> Result<String> in
.....
return newUrl
}
}
private func request2(credentials: Credentials) -> Observable<String> {
return request1()
.flatMapLatest { (newUrl)
return RxAlamofire
.requestString(.get, newUrl)
.flatMapLatest { (response, _) -> Observable<String> in
let params = ["username": credentials.username, "password": credentials.password]
return RxAlamofire
.requestString(.post, (response.url?.absoluteString)!, parameters: params)
.flatMapLatest { (response2,str) -> Observable<String> in
... some code formating ...
return RxAlamofire
.requestString(.post, actionUrl!, parameters: anotherParameters)
.map { return result }
}
}
}
}
when I am calling it it looks something like this :
result = someObservable.flatMapLatest { return ScrapingService.request2(credentials: $0) }
when I trigger "someObservable" it runs the request2 as expected, but the actual request is not made.
In the end I do onNext on the result.
when I am calling it it looks something like this :
result = someObservable.flatMapLatest { return ScrapingService.request2(credentials: $0) }
You're not "calling" the observable here. You are merely creating it. In order to get results from an Observable, you must subscribe to it.
I have the next function on Vapor:
func getPartidosHandler(_ req: Request) throws -> Future<[PartidoWSData]> {
return Partido.query(on: req).filter(\.estado == nil).all().map(to: [PartidoWSData].self) { partidos in
var partidosWS: [PartidoWSData] = []
for partido in partidos {
// Something here
}
return partidosWS
}
}
And the next struct PartidoWSData:
struct PartidoWSData: Content {
let idPartido: String
let fecha: String
let sede1: Future<Sede>
let sede2: Future<Sede>
}
My model Partido has two references to Sede, "sede1" and "sede2".
What I want is that the function gives an array of PartidoWSData struct, where I can see two properties of "Partido", "idPartido" and "fecha", and the two Sede related to the model.
How can I do that?
Thanks!
I'm not sure exactly what type of relation exists between Partido and Sedebecause the model wasn't included here, but assuming it's a Parent/Child relation, you should be able to do something like:
func getPartidosHandler(_ req: Request) throws -> Future<[PartidoWSData]> {
return Partido.query(on: req).filter(\.estado == nil).all().flatMap { partidos -> Future<[PartidoWSData]> in
let partidoIDs = try partidos.map { try $0.requireID() }
return Sede.query(on: req).filter(\.partidoID ~~ partidoIDs).map { sedes -> [PartidoWSData] in
return partidos.map { partido -> PartidoWSData in
return PartidoWSData(
id: partido.id
sedes: sedes.filter { $0.partidoID == partido.id }
)
}
}
}
}
The key is using the ~~ operator to do an x IN (...) predicate, following by using Array.filter to get the appropriate results.
I have a few async function which I'd like to run in series to avoid "callback hell" and simplify things I've written the following helper structure:
typealias AsyncCallback = (Bool) -> Void
typealias AsyncFunction = (AsyncCallback) -> Void
public struct AsyncHelpers {
public static func series(_ functions: [AsyncFunction], _ callback: #escaping AsyncCallback) {
var index = 0
var completed: AsyncCallback? = nil
completed = { success in
if success == false { callback(false); return }
index += 1
if index < functions.count {
functions[index](completed!)
return
}
callback(true)
}
functions[index](completed!)
}
}
AsyncHelpers.series([
{ callback in
// do async stuff
callback(true)
}, { callback in
// then do async stuff
callback(true)
}
]) { callback in
// when all completed
}
I can set the #escaping attribute for completion handler, but when I try to apply this attribute to [AsyncFunction] compilator fails with this error: "#escaping attribute only applies to function types". Should I mark these closured as escaping in other way, please?
What is lifecycle of index variable, can I use it inside completed closure without any problem?