Knockout计算似乎没有更新

时间:2013-11-18 13:47:26

标签: javascript unit-testing knockout.js qunit

我有一个简单的视图模型,我是单元测试,我似乎无法理解这种行为。我认为这可能与敲除有选择地跟踪依赖关系或缓存计算结果有关。

代码(represented in this fiddle):

function viewModel() {
 var serviceErrors = ko.observable([]),
     isCancelImmediately = ko.observable(true),
     futureDate = ko.observable(),
     errors = ko.computed(function() {
         var allErrors = serviceErrors(),
             isImmediate = isCancelImmediately(),
             selectedDate = futureDate();

         if(!selectedDate && !isImmediate) {
          allErrors.push('Please select a date if not immediate.');   
         }

         return allErrors;
     });

    return {
        futureDate: futureDate,
        errors: errors,
        isCancelImmediately: isCancelImmediately
    };
}
test('should give error if user has not selected a date when closing immediately', function() { 
    var sut = viewModel();

    ok(!sut.futureDate(), 'no date should be set to start with');    
    sut.isCancelImmediately(false);
    equal(sut.errors().length, 1, 'should contain a future date error if user hasn\'t entered a date');
    sut.futureDate('11/12/2014');
    equal(sut.futureDate(), '11/12/2014', 'should have set future date');
    equal(sut.errors().length, 0, 'should not be showing error');
});

有人可以告诉我为什么最后一个断言失败了吗?

1 个答案:

答案 0 :(得分:0)

我认为:

allErrors.push('Please select a date if not immediate.'); 

实际上是将字符串推送到serviceErrors observable包含的数组中。因此,当您对addErrors进行推送时,您也会推送到serviceErrors。