Challenge - 5 Problems
ViewModel Testing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ ui_behavior
intermediate2:00remaining
How does ViewModel update UI state?
Consider a ViewModel that updates a published property to change the UI. What will the UI show after calling
loadData() if the data fetch succeeds?iOS Swift
class SampleViewModel: ObservableObject { @Published var message = "" func loadData() { message = "Loading..." DispatchQueue.main.asyncAfter(deadline: .now() + 1) { self.message = "Data loaded" } } } let vm = SampleViewModel() vm.loadData() // After 2 seconds, what is vm.message?
Attempts:
2 left
💡 Hint
Think about asynchronous updates and when the message changes.
✗ Incorrect
The ViewModel first sets message to "Loading..." immediately, then after 1 second updates it to "Data loaded". After 2 seconds, the message is "Data loaded".
❓ lifecycle
intermediate1:30remaining
When is ViewModel deinitialized?
Given this ViewModel and usage, when will the
deinit print statement run?iOS Swift
class MyViewModel { deinit { print("ViewModel deinitialized") } } var vm: MyViewModel? = MyViewModel() vm = nil // When does "ViewModel deinitialized" print?
Attempts:
2 left
💡 Hint
Think about reference counting and when objects are freed.
✗ Incorrect
Setting vm to nil removes the last strong reference, so the ViewModel is deinitialized immediately.
🔧 Debug
advanced2:30remaining
Why does this ViewModel test fail?
This unit test expects the ViewModel's
isLoading to be false after fetchData(). Why does it fail?iOS Swift
class TestViewModel { var isLoading = false func fetchData() { isLoading = true DispatchQueue.global().async { sleep(1) self.isLoading = false } } } let vm = TestViewModel() vm.fetchData() assert(vm.isLoading == false) // Fails here
Attempts:
2 left
💡 Hint
Consider when the assert runs compared to the async update.
✗ Incorrect
The assert runs immediately after fetchData(), before the async block sets isLoading to false, so isLoading is still true at assert time.
🧠 Conceptual
advanced1:30remaining
What is the main benefit of unit testing ViewModels?
Why do developers write unit tests specifically for ViewModels in an iOS app?
Attempts:
2 left
💡 Hint
Think about separation of concerns in app architecture.
✗ Incorrect
ViewModels contain business logic and state, so testing them isolates logic from UI and external dependencies.
📝 Syntax
expert2:00remaining
What error does this ViewModel test code produce?
What error occurs when running this Swift unit test code?
iOS Swift
class VM { var count = 0 func increment() { count += 1 } } func testIncrement() { let vm: VM? = VM() vm.increment() assert(vm?.count == 1) } testIncrement()
Attempts:
2 left
💡 Hint
Look at how vm is declared and how increment() is called.
✗ Incorrect
vm is an optional, so calling vm.increment() without unwrapping causes a compile error.