Skip to content

What's the way to use assertSnapshot in async test? #822

Closed
@valeriyvan

Description

@valeriyvan

Please look below example of async test. Test with XCTAssertEqual works as expected but same test with assertSnapshot crashes.

What's the way to use assertSnapshot in async test?

struct AsyncSequenceExample: AsyncSequence {
    typealias Element = Int

    func makeAsyncIterator() -> AsyncIterator {
        print()
        return AsyncIterator()
    }

    struct AsyncIterator: AsyncIteratorProtocol {
        var current = 1

        mutating func next() async throws -> Element? {
            print("enter")
            try await Task.sleep(nanoseconds: 100_000_000) // Simulate an asynchronous operation
            defer { current += 1 }
            guard Int.random(in: 0..<100_000_000) > 1_000_000 else {
                return nil
            }
            print(current)
            return current
        }
    }
}

class MyTests: XCTestCase {
    func testAsyncSequence() async throws {
        let asyncSequence = AsyncSequenceExample()

        var result: [Int] = []
        do {
            for try await element in asyncSequence {
                result.append(element)
            }
        } catch {
            XCTFail("Unexpected error: \(error)")
        }

        // This test works as expected
        // XCTAssertEqual(result, [1, 2, 3])

        // But this crashes
        assertSnapshot(of: result.description, as: .lines)

    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions