如何在指令单元测试中模拟变量



我创建了一个自定义指令,并希望模拟一个变量以使测试正常工作。这是单元测试的一部分:

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

该指令在设置初始变量时调用服务。两个测试都失败了,因为在指令中我有一个名为 request 的变量,它没有被正确模拟。问题是我怎么能嘲笑这个?还是我需要将请求变量放在作用域上?这是代码的一部分:

 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 ref:http://plnkr.co/edit/juDwpot727jzxzzWeaJl?p=preview

您正在访问$parent范围内的对象,所以我要执行以下操作:

$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;

附言您的指令中还有另一个错误 - 您尝试访问scope.repairer而不是scope.Repairer

看看这个:http://plnkr.co/edit/OFTZff53BXGNLQqRfE8L?p=preview

最新更新