javascript - How to change constant value in a Karma test -
i have angular directive sets value of $scope property based on value of injected constant. want test value being correctly initialized constant, change constant's value within individual it block. (preferably within one, changing value between multiple blocks ok too)
is possible, , how can it?
simplified example:
//////// directive //////// angular.module('myapp.directives', []) .constant('the_constant', 'hello world') .directive('mydirective', ['the_constant', function (the_constant) { return { restrict: 'e', link: function ($scope) { $scope.propertybasedonconstant = the_constant; } }; }]); //////// test //////// describe('mydirective', function () { var $element, $scope; beforeeach(module('myapp.directives')); beforeeach(module(function ($provide) { $provide.constant('the_constant', 'foo'); })); beforeeach(inject(function ($rootscope, $compile) { $scope = $rootscope; $element = angular.element('<my-directive></my-directive>'); $compile($element)($scope); $scope.$digest(); })); aftereach(function () { $scope.$destroy(); $element.remove(); }); it("should correctly reflect constant's value", function() { expect( $scope.propertybasedonconstant ).to.equal('foo'); // want change constant's value , re-initialize directive }); });
you providing constant undefined module.
change beforeeach block , should work™:
var $scope, $element, mocked_constant; beforeeach(function () { mocked_constant = 'foo'; module('myapp.directives', function ($provide) { $provide.constant('the_constant', mocked_constant); }); inject(function ($rootscope, $compile) { $scope = $rootscope.$new(); // don't forget call .$new()! var template = angular.element('<my-directive></my-directive'); $element = $compile(template)($scope); // store reference compiled element, not raw string. $scope.$digest(); }); }); it("should correctly reflect constant's value", function() { expect( $scope.propertybasedonconstant ).to.equal(mocked_constant); // expect( $scope.propertybasedonconstant ).to.equal('foo'); }); if need change constant's value between it's, extract call module helper function, aswell inject. such as:
function setupmodule (constant) { module('myapp.directives', function ($provide) { $provide.constant('the_constant', constant); }); } function injectitall () { inject(function ($rootscope, $compile) { $scope = $rootscope.$new(); // don't forget call .$new()! var template = angular.element('<my-directive></my-directive'); $element = $compile(template)($scope); // store reference compiled element, not raw string. $scope.$digest(); }); } and in spec do:
it('equals banana', function () { setupmodule('banana'); injectitall(); expect($scope.propertybasedonconstant).to.equal('banana'); });
Comments
Post a Comment