2016-02-29 69 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