【发布时间】:2013-12-22 08:46:59
【问题描述】:
我在网页上有 Jasmine、Knockout 和 jQuery。我编写了一些测试,我认为这些测试可以验证视图模型是否以我期望的方式绑定到 DOM,但是 jQuery 似乎无法像我想象的那样模拟用户交互:
例如
<input type='text' id='someField' data-bind='value: someField'>
<script>
var viewModel = { someField: ko.observable() };
// ...
//this test passes
it('should update the DOM when I edit the model', function(){
$('#someField').val('not the test value');
viewModel.someField('test value');
expect( $('#someField').val() ).toBe('test value');
});
//this test does not
it('should update the model when I change the DOM', function(){
viewModel.someField('not the test value');
$('#someField').val('test value');
expect( viewModel.someField() ).toBe('test value');
});
</script>
第一个测试通过,第二个测试失败。当我实际手动编辑 someField 时,视图模型确实发生了变化;只有测试失败,而不是它正在测试的行为。手动编辑页面时,视图模型更新似乎发生'onblur',所以我将测试中的相关行更改为:
$('#someField').val('test value').next('input').focus();
但还是失败了。
我对单选按钮进行了类似的测试。当我手动单击它们时,视图模型确实发生了变化,但在测试中,调用 $('#radioButton').click(); 不会更新视图模型。
为什么 Knockout 无法识别 jQuery 对 DOM 的更改?
【问题讨论】:
标签: javascript jquery knockout.js jasmine