[英]How to test the UI Binding between RxSwift Variable and RxCocoa Observable?
I have a simple ViewModel
with one property: 我有一个简单的
ViewModel
具有一个属性:
class ViewModel {
var name = Variable<String>("")
}
And I'm binding it to its UITextField
in my ViewController
: 然后将其绑定到
ViewController
UITextField
:
class ViewController : UIViewController {
var viewModel : ViewModel!
@IBOutlet weak var nameField : UITextField!
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
// Binding
nameField.rx.text
.orEmpty
.bind(to: viewModel.name)
.disposed(by: disposeBag)
}
}
Now, I want to Unit Test it. 现在,我要对其进行单元测试。
I'm able to fill the nameField.text
property though Rx using .onNext
event - nameField.rx.text.onNext("My Name Here")
. 我可以使用
.onNext
事件通过Rx填充nameField.text
属性nameField.rx.text.onNext("My Name Here")
。
But the viewModel.name
isn't being filled. 但是
viewModel.name
没有被填充。 Why? 为什么? How can I make this Rx behavior work in my XCTestCase?
如何在XCTestCase中使这种Rx行为起作用?
Please see below the result of my last test run: 请在下面查看我上一次测试的结果:
I believe the issue you are having is that the binding is not explicitly scheduled on the main thread. 我相信您遇到的问题是绑定没有在主线程上显式安排。 I recommend using a
Driver
in this case: 我建议在这种情况下使用
Driver
:
class ViewModel {
var name = Variable<String>("")
}
class ViewController: UIViewController {
let textField = UITextField()
let disposeBag = DisposeBag()
let vm = ViewModel()
override func viewDidLoad() {
super.viewDidLoad()
textField.rx.text
.orEmpty
.asDriver()
.drive(vm.name)
.disposed(by: disposeBag)
}
// ..
With a Driver
, the binding will always happen on the main thread and it will not error out. 使用
Driver
,绑定将始终在主线程上进行,并且不会出错。
Also, in your test I would call skip
on the binding: 另外,在您的测试中,我将在绑定上调用
skip
:
sut.nameTextField.rx.text.skip(1).onNext(name)
because the Driver
will replay the first element when it subscribes. 因为
Driver
将在订阅时重播第一个元素。
Finally, I suggest using RxTest and a TestScheduler
instead of GCD. 最后,我建议使用RxTest和
TestScheduler
代替GCD。
Let me know if this helps. 让我知道是否有帮助。
rx.text relies on the following UIControlEvents: .allEditingEvents
and .valueChanged
. rx.text依赖于以下UIControlEvents:
.allEditingEvents
和.valueChanged
。 Thus, explicitly send a onNext events will not send action for these event. 因此,显式发送onNext事件将不会为这些事件发送动作。 You should send action manually.
您应该手动发送操作。
sut.nameField.rx.text.onNext(name)
sut.nameField.sendActions(for: .valueChanged)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.