Search code examples
angularjsunit-testingangularjs-directivejasminespy

How to mock variable in directive unit test?


I have created a custom directive and would like to mock out a variable to make the test working. This is part of the unit test:

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

The directive is calls a service when the initial-variable is set. Both tests are failing because in the directive I have a variable called request that is not properly mocked. The question is how can I mock this out? Or do I need to put the request variable on scope? This is part of the code:

 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


Solution

  • You are accessing an object on the $parent scope, so I'de do somthing like:

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

    However, your code is problematic since it's asuming a lot about this 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. you had another error in your directive - you tried accessing scope.repairer instead of scope.Repairer

    check out this: http://plnkr.co/edit/OFTZff53BXGNLQqRfE8L?p=preview