-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathTimerPublisher_Tests.swift
More file actions
98 lines (72 loc) 路 2.97 KB
/
Copy pathTimerPublisher_Tests.swift
File metadata and controls
98 lines (72 loc) 路 2.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
//
// Copyright 漏 2026 Stream.io Inc. All rights reserved.
//
import Combine
@testable @preconcurrency import StreamVideo
import XCTest
final class TimerPublisher_Tests: XCTestCase, @unchecked Sendable {
private var disposableBag: DisposableBag! = .init()
private var receivedDates: [Date]! = []
// MARK: - Emits values while active subscriptions exist
func test_receive_whenSubscribed_emitsDates() async {
let expectation = expectation(description: "Should emit at least one value")
let subject = TimerPublisher(interval: 0.2)
subject
.prefix(3)
.sink { [weak self] date in
self?.receivedDates.append(date)
if self?.receivedDates.count == 3 {
expectation.fulfill()
}
}
.store(in: disposableBag)
await fulfillment(of: [expectation])
}
// MARK: - Suspends timer when all subscriptions are cancelled
func test_receive_whenSubscriptionCancelled_timerSuspends() async throws {
let subject = TimerPublisher(interval: 0.2)
let expectation = expectation(description: "Timer should suspend after cancel")
subject
.sink { [weak self] in self?.receivedDates.append($0) }
.store(in: disposableBag)
Task {
try? await Task.sleep(nanoseconds: 250_000_000)
disposableBag.removeAll()
try? await Task.sleep(nanoseconds: 350_000_000)
let countAfterCancel = receivedDates.count
try? await Task.sleep(nanoseconds: 200_000_000)
XCTAssertEqual(receivedDates.count, countAfterCancel)
expectation.fulfill()
}
await fulfillment(of: [expectation], timeout: 1)
}
// MARK: - Resumes timer after new subscription
func test_receive_whenResubscribed_timerResumes() async {
let subject = TimerPublisher(interval: 0.2)
let firstValueExpectation = expectation(description: "Should receive first value")
let expectation = expectation(description: "Should receive values after resubscription")
var cancellable = subject
.log(.debug) { "Received value: \($0.millisecondsSince1970)" }
.sink { [weak self] in
self?.receivedDates.append($0)
if self?.receivedDates.count == 1 {
firstValueExpectation.fulfill()
}
}
await fulfillment(of: [firstValueExpectation], timeout: 1)
cancellable.cancel()
XCTAssertEqual(receivedDates.count, 1)
receivedDates = []
await wait(for: 0.25)
XCTAssertTrue(receivedDates.isEmpty)
cancellable = subject
.prefix(2)
.sink { [weak self] in
self?.receivedDates.append($0)
if self?.receivedDates.count == 2 {
expectation.fulfill()
}
}
await fulfillment(of: [expectation])
}
}