Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
valeriyvan opened this issue Jan 4, 2024 · 3 comments
Open

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

valeriyvan opened this issue Jan 4, 2024 · 3 comments

Comments

@valeriyvan
Copy link
Contributor

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)

    }
}
@dwroth
Copy link

dwroth commented Mar 14, 2024

The problem is the use of XCTWaiter.wait inside of verifySnapshot. Using the synchronous wait function in an asynchronous context is a known issue (that's why Apple introduced await fulfillment(of:).

@tejassharma96
Copy link

Is this crash Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Current context must not be nil'? If so, I am hitting that issue too in an async test :/ is there any workaround that we can use until the library can be updated to support some sort of await assertSnapshot method?

@tejassharma96
Copy link

Actually, I did find that marking all the async tests as @MainActor works, so there's that... still frustrating but I suppose it works now :/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants