【问题标题】:How to mock variable in directive unit test?如何在指令单元测试中模拟变量?
【发布时间】:2016-06-11 23:46:18
【问题描述】:

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

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

【问题讨论】:

    标签: angularjs unit-testing angularjs-directive jasmine spy


    【解决方案1】:

    您正在访问$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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-20
      • 2019-06-25
      • 1970-01-01
      • 1970-01-01
      • 2019-08-26
      • 2020-06-13
      相关资源
      最近更新 更多