2016-02-29 78 views
0

我已經創建了一個自定義指令,並想模擬一個變量來使測試工作。這是單元測試的一部分:如何在指令單元測試中模擬變量?

it('should pass on initialvalue', function() { 
    scope.$apply(function() { 
     scope.initial = 2; 
     scope.Repairer = null; 
    }); 
    expect(elementScope.initial).toEqual(2); 
    }); 

該指令在設置初始變量時調用服務。兩個測試都失敗了,因爲在這個指令中我有一個叫做請求的變量沒有被正確地模擬。問題是我該如何嘲笑這件事?或者我需要將請求變量放在作用域上?這是部分代碼:

if (scope.Repairer) { 

         console.log('calling scriptservice'); 
         var request = { 
          allocationProcess: (scope.$parent.lodgement.searchSettings.automatic.visible) ? 'automatic' : 'direct', 
          allocationSource: 'internal', 
          brand: brandScriptTag, // lookup brand scripting name 
          includeSegment: false, 
          relationship: scope.repairer.relationshipCode, 
          ruralSearch: scope.repairer.isRural, 
          state: scope.$parent.lodgement.claimLocation 

         }; 
         scriptingService.getScript(request).then(function (scripts) { 
          scope.scripts = scripts; 
         }); 
        } else { 
         scope.scripts = null; 
        } 

plunker裁判:http://plnkr.co/edit/juDwpot727jzxzzWeaJl?p=preview

回答

0

您在$parent範圍訪問對象,所以I'de做財產以後這樣的:

$rootScope.lodgement = jasmine.any(Object); 

但是,您的代碼是有問題的,因爲它正在假設很多關於這個lodgement ...

//it's better to use jasmine.any(Object) 
//$rootScope.lodgement = jasmine.any(Object); 
var lodgement_mock = {searchSettings:{automatic:{visible:false}}}; 
$rootScope.lodgement = lodgement_mock; 

p.s. 你在你的指令有另一個錯誤 - 你試圖訪問scope.repairer代替scope.Repairer

看看這個: http://plnkr.co/edit/OFTZff53BXGNLQqRfE8L?p=preview