AngularJS 2.0 - How to test the application?

I am building an AngularJS application (using ES6) with the same amount of AngularJS 2.0, so I wonโ€™t have much work with porting.

As you know, there will be no controllers, as we know them in <= v1.4

Sample code for one of my directives

class LoginSidebar { constructor() { } someMethod(){ } } LoginSidebar.$inject = []; export default function() { return { scope: {}, templateUrl: 'tpl/path/to/loginSidebar.tpl.html', replace: true, controller: LoginSidebar, controllerAs: 'loginSidebarCtrl' }; }; 

Here is what app.js looks like

 import loginSidebar from "./js/component/loginSidebar/LoginSidebar.js"; angular.module('myModule', [ 'ngNewRouter', 'ngAnimate' ]) .directive("loginSidebar", loginSidebar); 

As you can see, I don't have .controller() there, since I have to test methods inside the class?

PS. I tried using Karma-Jasmine, but I need to check the whole directive, and if I do, I get the error I wrote here: AngularJS and Karma-Jasmine - How to ignore templateUrl to avoid "Unexpected request: GET ... /. html "

+5
source share
1 answer

You can define a controller with a global name, and then specify it in the directive:

 //LoginSidebarController.js class LoginSidebarController { // controller code here } export default LoginSidebarController //LoginSidebarDirective.js export default function() { return { scope: {}, templateUrl: 'tpl/path/to/loginSidebar.tpl.html', replace: true, controller: 'LoginSidebarController', controllerAs: 'loginSidebarCtrl' }; }; //app.js import loginSidebarDirective from "./js/component/loginSidebar/LoginSidebarDirective.js"; import LoginSidebarController from "./js/component/loginSidebar/LoginSidebarController.js"; angular.module('myModule', []) .directive('loginSidebar', loginSidebarDirective) .controller('LoginSidebarController', LoginSidebarController) 

Then you can require the controller, like another ordinary controller, to check it regardless of the directive.

As a second way, you can access the controller using the angular.element().controller('loginSidebar') . Something like that:

 var testElm = angular.element('<login-sidebar />'); $compile(testElm); testElm.controller('loginSidebar') 
0
source

All Articles