angularjs - How to test controller separately? -
i have controller changing dom different places.
the controller is:
angular.module('mymodule').controller('mycontroller', mycontroller); function mycontroller() { this.addsomeclass = function() { $('#idofsomeelement').addclass('someclass'); }; }
and used this. inside different components , html.
<div id="idofsomeelement"></div> . . . <some-angular-component-here> <div ng-controller="mycontroller ctrl"> <div ng-click="ctrl.addsomeclass()"></div> </div> </some-angular-component-here> . . . <using-in-onother-place> <div ng-controller="mycontroller ctrl"> <div ng-click="ctrl.addsomeclass()"></div> </div> </using-in-onother-place>
i try test this, have undefined ctrl.
describe('controller test', function () { 'use strict'; var ctrl, element; beforeeach(inject(function ($rootscope, $compile) { var scope = $rootscope.$new(); angular.element('<div id="idofsomeelement"></div>' + '<div ng-controller="mycontroller ctrl">' + '<div id="button" ng-click="ctrl.addsomeclass()"></div>' + '</div>'); element = $compile(element)(scope); scope.$apply(); // how controller here linked html? ctrl = $controller('mycontroller'); ctrl = element.controller('mycontroller'); })); it('should add class', function () { var button = $(element).find('#button')[0]; $(button).trigger('click'); var someelement = $(element).find('#idofsomeelement')[0]; expect(someelement).tohavesomeclass(); }); });
how correct test kind of controller? , know manipulate dom inside controller bad thing need unit test it.
thanks
i think forgot assign return value of angular.element element property...
element = angular.element(....
complete beforeeach:
beforeeach(inject(function ($rootscope, $compile) { var scope = $rootscope.$new(); element = angular.element('<div id="idofsomeelement"></div>' + '<div ng-controller="mycontroller ctrl">' + '<div id="button" ng-click="ctrl.addsomeclass()"></div>' + '</div>'); element = $compile(element)(scope); scope.$apply(); // how controller here linked html? ctrl = $controller('mycontroller'); ctrl = element.controller('mycontroller'); }));
Comments
Post a Comment