angularjs - Cannot get the scope os a controller in anugular.js -
i trying test javascript file has in controller , html dom elements interacts with.
the class under test is:
function baseconceptmenu(options) { var baseconceptmenu = new basemenu(options); //public function -->method under test function showcodeconcepttoolbar() { var scope = angular.element('#toolbar').scope(); scope.$apply(function() { scope.toolbarcontroller.show(baseconceptmenu.someobject); }); }
i trying mock controller , create html dom element "toolbar" on fly without trying create external html template sake of testing.
i trying create div "toolbar" inside before each , mocking "codeconcepttoolbarcontroller" controller
beforeeach(inject(function ($rootscope, $compile) { elm = document.createelement('div'); elm.id = 'toolbar'; scope = $rootscope.$new(); createcontroller = function() { return $controller('codeconcepttoolbarcontroller', { $scope: scope }); }; $compile(elm)(scope); scope.$digest(); }));
however when try test below
it('test code conepttoolbarcontoller', function() { // var toolbar = angular.element('#toolbar'); document.getelementbyid("toolbar").scope().toolbarcontroller = createcontroller(); //as of now,not doing any-idepth testing //just base test call var menu = new baseconceptmenu({}); expect(menu.show()).tobe(true); });
i error
typeerror: cannot read property 'scope' of null
could provide way test this? or there better way test this? using maven-jasmine plugin
two problems:
as per https://developer.mozilla.org/en-us/docs/web/api/document.getelementbyid, "elements not in document not searched getelementbyid." $compile doesn't insert element dom - sets appropriate bindings (and smart things handling nested directives inside template string). getelementbyid fail find match. need insert element dom somewhere.
getelementbyid returns raw html dom element. angular scope it, docs call wrapping in angular.element():
var element = document.getelementbyid(id); angular.element(element).scope()...
this pattern provide angular wrapper around element rest of magic. it's based on jqlite, isn't jquery follow lot of same patterns. used jquery, think of writing $(element)
.
Comments
Post a Comment