等待Observable到达完成状态

时间:2018-08-04 19:25:13

标签: ios rx-swift rxtest

我具有如下所示的设置,并且想要测试 .empty 状态。

// MARK: - States
enum State {
    case loading(Bool)
    case error(SerializedNetworkError?)
    case empty
}

// MARK: - Properties
private(set) var pokemonCellModels = BehaviorRelay<[PokemonTableViewCellModel]>(value: [])
private(set) var viewState = BehaviorRelay<State>(value: .loading(true))

// MARK: - API Calls
func loadPokemons() {
    viewState.accept(.loading(true))
    services.getPokemonList().subscribe(onNext: { pokemonListResponse in
        guard let results = pokemonListResponse?.results, results.count > 0 else {
            self.viewState.accept(.empty)
            return
        }
        let viewModelsForResult = results.map({ (listItem) -> PokemonTableViewCellModel in
            return PokemonTableViewCellModel(listItem: listItem)
        })
        if viewModelsForResult.count == 0 {
            self.viewState.accept(.empty)
        }
        self.pokemonCellModels.accept(viewModelsForResult)
    }, onError: { (error) in
        let networkError = error as! NetworkError
        self.viewState.accept(.error(networkError.requestError))
    }, onCompleted: {
        self.viewState.accept(.loading(false))
    }).disposed(by: disposeBag)
}

我的方法 services.getPokemonList 返回我的响应模型的可观察值。 为了进入 .empty 状态,我的api需要返回一个空数组或nil结果。 我应该在viewState [ .loading(true)、. loading(true)、. loading(false)、. empty ]上有4个事件,在pokemonCellModels [ [],[] < / strong>] 但是我不确定如何使我的测试代码获得所有这些事件。 我正在使用RxTests并尝试使用RxBlocking。

我拥有的测试代码是这样:

func testEmptyState() {
    // Given
    let actionsDelegateStub = HomeViewControllerActionsDelegateStub()
    let mockURL = URL(string: "http://someurl.com")!
    let mockedSession = MockURLSession(data: nil, response: nil, error: nil)
    let mockedNetworkDispatcher = NetworkDispatcher(url: mockURL, session: mockedSession)
    let mockedPokemonServices = PokemonService(dispatcher: mockedNetworkDispatcher)

    // When
    let sut = HomeViewModel(actionsDelegate: actionsDelegateStub, services: mockedPokemonServices)
    let viewStateResults = testScheduler.createObserver(HomeViewModel.State.self)

    testScheduler.scheduleAt(0) {
        sut.viewState.subscribe(viewStateResults.asObserver()).disposed(by: self.disposeBag)
    }

    sut.loadPokemons()

    testScheduler.start()

    // Then
    let viewStateExpectedResults: [HomeViewModel.State] = [.loading(true), .loading(true), .loading(false), .empty]
    var colectedViewStates = [HomeViewModel.State]()
    for event in viewStateResults.events {
        guard let element = event.value.element else { return }
        colectedViewStates.append(element)
    }
    XCTAssertEqual(viewStateExpectedResults, colectedViewStates)
}

有人可以帮我看看我在做什么错吗? 我是RxSwift测试的新手。 我想我需要等待services.getPokemonList到达“ onCompleted状态” ...

0 个答案:

没有答案