Skip to content

Commit a49b543

Browse files
chore: Fix SSE manager flaky test (#1025)
1 parent 9db22cf commit a49b543

File tree

1 file changed

+16
-12
lines changed

1 file changed

+16
-12
lines changed

Tests/MessagingInApp/Gist/Network/SSE/SseConnectionManagerTest.swift

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -251,24 +251,28 @@ class SseConnectionManagerTest: XCTestCase {
251251
}
252252

253253
func test_serverEvent_givenHeartbeatEvent_expectHeartbeatTimerRestarted() async {
254-
// Setup
255-
let (stream, continuation) = AsyncStreamBackport.makeStream(of: SseEvent.self)
254+
// Setup: resume when startTimer is called the second time
255+
let (stream, streamContinuation) = AsyncStreamBackport.makeStream(of: SseEvent.self)
256256
sseServiceMock.connectReturnValue = stream
257257

258+
let secondStartTimerReceived = Task {
259+
await withCheckedContinuation { (cont: CheckedContinuation<Void, Never>) in
260+
heartbeatTimerMock.startTimerClosure = { [weak heartbeatTimerMock] _, _ in
261+
guard let mock = heartbeatTimerMock, mock.startTimerCallsCount == 2 else { return }
262+
cont.resume()
263+
}
264+
}
265+
}
266+
258267
// Action
259268
await sut.startConnection()
269+
streamContinuation.yield(.connectionOpen)
270+
streamContinuation.yield(.serverEvent(ServerEvent(id: nil, type: "heartbeat", data: "{\"heartbeat\": 30}")))
271+
streamContinuation.finish()
260272

261-
// First establish connection
262-
continuation.yield(.connectionOpen)
263-
try? await Task.sleep(nanoseconds: 50000000) // 0.05 seconds
264-
265-
// Then receive heartbeat
266-
let heartbeatEvent = ServerEvent(id: nil, type: "heartbeat", data: "{\"heartbeat\": 30}")
267-
continuation.yield(.serverEvent(heartbeatEvent))
268-
try? await Task.sleep(nanoseconds: 100000000) // 0.1 seconds
269-
continuation.finish()
273+
await secondStartTimerReceived.value
270274

271-
// Assert: Timer should be started multiple times (once for connection, once for heartbeat)
275+
// Assert: Timer started for connection open and again for heartbeat
272276
XCTAssertGreaterThanOrEqual(heartbeatTimerMock.startTimerCallsCount, 2)
273277
}
274278

0 commit comments

Comments
 (0)