SwiftUI Academy · Lección

Probar código asíncrono

Verifique de forma fiable los flujos de async/await.

Lección 2 de 413 pasos

Probar código asíncrono es una lección gratuita de SwiftUI Academy en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de SwiftUI Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de SwiftUI Academy incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Async Needs Special Care

Network calls and tasks finish later, not instantly. Your tests must wait for the result before asserting, or they check too early. ⏳

Mark the Test async

The simplest fix is an async test method. Swift lets you await directly, and the runner pauses until the work completes.

func testLoad() async {
}

Await Your Method

Inside an async test you can use await just like real code. The line pauses until your ViewModel finishes loading.

await vm.load()

Assert After Awaiting

Once the await returns, the data is ready. Now your assertion checks the final state, not an empty one. ✅

XCTAssertEqual(vm.items.count, 3)

Throwing Async Tests

If the code can throw, mark the test throws too. Then try await lets errors bubble up and fail the test cleanly.

func testFetch() async throws {
  try await vm.fetch()
}

Avoid Real Networks

Hitting a live server makes tests slow and flaky. Inject a mock service that returns fixed data instead.

A Mock Service

A mock conforms to the same protocol but returns canned values. Your ViewModel cannot tell the difference, so the logic is tested honestly.

struct MockAPI: API {
  func load() async -> [Item] { sample }
}

Testing the Error Path

Make your mock throw on demand. Then you can verify the ViewModel sets an error state instead of crashing.

Expectations for Callbacks

For older callback APIs, use an XCTestExpectation. Fulfill it inside the callback, then wait so the test does not end early.

let exp = expectation(description: "done")

Wait With a Timeout

Pair every expectation with a timeout. If the callback never fires, the test fails fast instead of hanging forever.

await fulfillment(of: [exp], timeout: 2)

Prefer async Over Callbacks

When you can, write code with async/await. Tests stay short, linear, and far easier to read than nested callbacks.

Quick Check

How should you wait for async work in a modern XCTest?

Recap

You can now test async code: mark tests async, await results, mock the network, and use expectations for callbacks. Reliable every run. 🎉

Gratis para empezar

Aprende Swift con un tutor de IA — gratis

Escribe y ejecuta código real en tu navegador, obtén ayuda instantánea de un tutor de IA disponible 24/7 y continúa donde lo dejaste en la web o en la aplicación.

Cursos
30
Lecciones
120

Preguntas frecuentes

¿La lección «Probar código asíncrono» es gratis?

Sí — el texto completo de «Probar código asíncrono» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de SwiftUI Academy, actualiza a CoddyKit PRO. El curso de SwiftUI Academy incluye 4 lecciones en total.

¿Qué aprenderé en «Probar código asíncrono»?

Verifique de forma fiable los flujos de async/await. Practicas SwiftUI Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar SwiftUI Academy?

No se requiere experiencia previa. SwiftUI Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.

¿Cuánto tiempo toma la lección «Probar código asíncrono»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de SwiftUI Academy?

Sí. Cada lección de SwiftUI Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Pruebas unitarias de ViewModels
  2. Probar código asíncrono
  3. Pruebas de interfaz con XCUITest
  4. Pruebas con snapshots y previews
← Volver a SwiftUI Academy