JordanCoin/ios-skills-collection / skills/bocato--swift-testing
swift-testing
VerifiedExpert guidance on Swift Testing best practices, patterns, and implementation. Use when developers mention: (1) Swift Testing, @Test, #expect, #require, or @Suite, (2) "use Swift Testing" or "modern testing patterns", (3) test doubles, mocks, stubs, spies, or fixtures, (4) unit tests, integration tests, or snapshot tests, (5) migrating from XCTest to Swift Testing, (6) TDD, Arrange-Act-Assert, or F.I.R.S.T. principles, (7) parameterized tests or test organization.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 9.5 KB |
| references/_index.md | markdown | 2.7 KB |
| references/async-testing.md | markdown | 4.7 KB |
| references/dump-snapshot-testing.md | markdown | 6.2 KB |
| references/fixtures.md | markdown | 4.2 KB |
| references/integration-testing.md | markdown | 4.5 KB |
| references/migration-xctest.md | markdown | 5.5 KB |
| references/parameterized-tests.md | markdown | 4.0 KB |
| references/snapshot-testing.md | markdown | 4.3 KB |
| references/test-doubles.md | markdown | 6.0 KB |
| references/test-organization.md | markdown | 4.0 KB |
references/async-testing.md
View on GitHub# Async Testing
Testing asynchronous code with Swift Testing.
## Basic Async Tests
```swift
@Test func asyncOperation() async {
let result = await service.fetch()
#expect(result.isValid)
}
@Test func asyncThrowingOperation() async throws {
let data = try await service.fetchData()
#expect(!data.isEmpty)
}
```
## Testing Async Sequences
```swift
@Test func asyncSequence() async {
let sequence = Counter().values
var collected: [Int] = []
for await value in sequence.prefix(3) {
collected.append(value)
}
#expect(collected == [1, 2, 3])
}
```
## Confirmation (for callbacks/delegates)
Use `confirmation` when testing delegate patterns or callbacks:
```swift
@Test func delegateCallback() async {
await confirmation { confirm in
let delegate = TestDelegate(onComplete: {
confirm()
})
service.delegate = delegate
service.performAction()
}
}
```
### Multiple Confirmations
```swift
@Test func multipleCallbacks() async {
await confirmation(expectedCount: 3) { confirm in
let observer = Observer(onEvent: { _ in
confirm()
})
emitter.emit(.event1)
emitter.emit(.event2)
emitter.emit(.event3)
}
}
```
### Optional Confirmation
```swift
@Test func optionalCallback() async {
await confirmation(expectedCount: 0...1) { confirm in
// May or may not be called
service.maybeNotify { confirm() }
}
}
```
## Testing Timeouts
### Built-in Time Limit
```swift
@Test(.timeLimit(.seconds(5)))
func mustCompleteQuickly() async {
await slowOperation()
}
```
### Custom Timeout
```swift
@Test func withCustomTimeout() async throws {
try await withTimeout(seconds: 2) {
try await service.fetch()
}
}
func withTimeout<T>(
seconds: Double,
operation: @escaping () async throws -> T
) async throws -> T {
try await withThrowingTaskGroup(of: T.self) { group in
group.addTask { try await operation() }
group.addTask {
try await Task.sleep(for: .seconds(seconds))
throw TimeoutError()
}
let result = try await group.next()!
group.cancelAll()
return result
}
}
```
## Testing Cancellation
```swift
@Test func cancellation() async {
let task = Task {
try await longRunningOperation()
}
// Give it time to start
try? await Task.sleep(for: .milliseconds(100))
task.cancel()
do {
_ = try await task.value
Issue.record("Should have been cancelled")
} catch is CancellationError {
// Expected
}
}
```
## Testing Actors
```swift
actor Counter {
var value = 0
func increment() { value += 1 }
}
@Test func actorState() async {
let counter = Counter()
await counter.increment()
await counter.increment()
let value = await counter.value
#expect(value == 2)
}
```
## Testing MainActor Code
```swift
@MainActor
class ViewModel {
var items: [Item] = []
func load() async {
items = await fetchItems()
}
}
@Test @MainActor
func viewModelLoading() async {
let viewModel = ViewModel()
await viewModel.load()
#expect(!viewModel.items.isEmpty)
}
```
## Mocking Async Dependencies
```swift
struct APIClient {
var fetch: @Sendable (URL) async throws -> Data
}
@Test func withMockedClient() async throws {
let mockData = "test".data(using: .utf8)!
let client = APIClient(
fetch: { _ in mockData }
)
let service = Service(client: client)
let result = try await service.getData()
#expect(result == mockData)
}
```
## Testing Debounced Operations
```swift
@Test func debounce() async throws {
let debouncer = Debouncer(delay: .milliseconds(100))
var callCount = 0
// Rapid calls
for _ in 1...5 {
await debouncer.submit {
callCount += 1
}
}
// Wait for debounce
try await Task.sleep(for: .milliseconds(150))
#expect(callCount == 1) // Only last call executed
}
```
## Testing Retry Logic
```swift
@Test func retryOnFailure() async throws {
var attempts = 0
let service = Service(
fetch: {
attempts += 1
if attempts < 3 {
throw NetworkError.timeout
}
return Data()
}
)
let result = try await service.fetchWithRetry(maxAttempts: 3)
#expect(attempts == 3)
#expect(result != nil)
}
```
## Best Practices
1. **Use async/await directly**: No need for expectations/wait
2. **Use confirmation for callbacks**: When testing delegate patterns
3. **Set time limits**: Prevent hanging tests
4. **Test cancellation**: Ensure proper cleanup
5. **Mock async dependencies**: Use closures for testability
6. **Run on correct actor**: Use @MainActor for UI tests
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| finishing-a-development-branchobra/superpowersUse when implementation is complete, all tests pass, and you need to decide how to integrate the work | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| systematic-debuggingobra/superpowersUse when encountering any bug, test failure, or unexpected behavior, before proposing fixes | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| test-driven-developmentobra/superpowersUse when implementing any feature or bugfix, before writing implementation code | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| skill-creatoranthropics/skillsCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |