Call a controller function from Karma and Jasmine testing - javascript

This is my angular controller :-
angular.module('authoring-controllers', []).
controller('NavCtrl', function($scope, $location, BasketNavigationService) {
$scope.test= function() {
$scope.testVar = BasketNavigationService.showBasketList();
};
});
TEST class
describe('NavCtrl', function() {
var scope, $location, createController;
beforeEach(inject(function ($rootScope, $controller, _$location_) {
$location = _$location_;
scope = $rootScope.$new();
createController = function() {
return $controller('NavCtrl', {
'$scope': scope
});
};
}));
it('should create $scope.testVar when calling test',
function() {
expect(scope.testVar).toBeUndefined();
scope.test();
expect(scope.testVar).toBeDefined();
});
});
Getting an error when i run that test case :- scope.test() is undefined..
If i removed BasketNavigationService functionality from controller then it is working..
Please help me to solve that karma test case.

here is the working demo , hope it helps.
problem was with injecting the dependencies.
//--- CODE --------------------------
(function(angular) {
// Create module
var myApp = angular.module('myApp', []);
// Controller which counts changes to its "name" member
myApp.controller('MyCtrl', ['$scope', 'BasketNavigationService',
function($scope, BasketNavigationService) {
$scope.test = function() {
$scope.testVar = BasketNavigationService.showBasketList();;
};
}
]);
})(angular);
// ---SPECS-------------------------
describe('myApp', function() {
var scope,
controller;
beforeEach(function() {
module('myApp');
});
describe('MyCtrl', function() {
beforeEach(inject(function($rootScope, $controller) {
scope = $rootScope.$new();
controller = $controller('MyCtrl', {
'$scope': scope,
'BasketNavigationService': {
showBasketList: function() {
return null;
}
}
});
}));
it('should create $scope.testVar when calling test',
function() {
expect(scope.testVar).toBeUndefined();
scope.test();
// scope.$digest();
expect(scope.testVar).toBeDefined();
});
});
});
// --- Runner -------------------------
(function() {
var jasmineEnv = jasmine.getEnv();
jasmineEnv.updateInterval = 1000;
var htmlReporter = new jasmine.HtmlReporter();
jasmineEnv.addReporter(htmlReporter);
jasmineEnv.specFilter = function(spec) {
return htmlReporter.specFilter(spec);
};
var currentWindowOnload = window.onload;
window.onload = function() {
if (currentWindowOnload) {
currentWindowOnload();
}
execJasmine();
};
function execJasmine() {
jasmineEnv.execute();
}
})();
<script src="http://jasmine.github.io/1.3/lib/jasmine.js"></script>
<script src="http://jasmine.github.io/1.3/lib/jasmine-html.js"></script>
<script src="https://code.angularjs.org/1.2.9/angular.js"></script>
<script src="https://code.angularjs.org/1.2.9/angular-mocks.js"></script>
<link href="http://jasmine.github.io/1.3/lib/jasmine.css" rel="stylesheet" />
fiddle : http://jsfiddle.net/invincibleJai/pf1deoom/1/

Please change your createController setup to:
createController = function() {
return $controller('NavCtrl', {
'$scope': scope,
'$location':$location,
'BasketNavigationService':{showBasketList: function(){return 'test'} }
});
};
You are not injecting all the dependencies.
I have injected dummy BasketNavigationService, you can inject the real one.

Have you tried running createController();? I don't think your NavCtrl controller gets mocked.

Related

Angular 1.5 test component with jasmine

I try test my component with Jasmine and Angular-mock, but I don't know how this do.
This is my component
var angular = require('angular');
'use strict';
module.exports = angular
.module('app.login.component.login', [])
.component('login', {
templateUrl: '/app/js/login/components/login.template.html',
controller: LoginController
});
LoginController.$inject = ['$state', 'Auth', 'messages'];
function LoginController($state, Auth, messages) {
var ctrl = this;
ctrl.failMessage = messages.NO_AUTH;
ctrl.failResponse = false;
ctrl.login = login;
function login(user){
ctrl.errors = {};
Auth.login(user)
.success(function(result){
$state.go('profile');
})
.error(function(response) {
ctrl.failResponse = true;
})
};
}
I write this test but his dosen't work.
Please explain me what I do wrong and show some pattern how test component
describe('Component: login', function() {
beforeEach(angular.mock.module(require('angular-ui-router')));
beforeEach(angular.mock.module(loginComponent.name));
var scope;
beforeEach(inject(function($rootScope, $compile){
scope = $rootScope.$new();
}));
var controller;
beforeEach(inject(function($componentController, Auth) {
ctrl = $componentController('login', {
$scope:scope});
}));
it('df', function() {
expect(ctrl.login).toBeDefined();
});
});
You use $componentController.
beforeEach(inject(function($rootScope, $componentController){
scope = $rootScope.$new();
controller = $componentController('myComponent', {$scope: scope});
}));

Error while Creating Angular JS Jasmine Test Case

I am creating Angular JS Jasmine Test Case. My code JS as follows:-
var app = angular.module("myApp", ['ngSanitize']);
app.controller("PatientDefectManagementCtrl", function ($scope, angularService) {
$scope.getNextAccountInfo = function () {
$scope.data = {message: 'Hello'};
}
});
I am getting error : Error: [ng:areq]
http://errors.angularjs.org/1.4.0-rc.2/ng/areq?p0=PatientDefectManagementCtrl&p1=not%20a%20function%2C%20got%20undefined**
My Test Case as follows:-
describe('Patient Defect Management Testing ', function () {
module('myApp');
var $controller;
beforeEach(inject(function (_$controller_) {
$controller = _$controller_;
}));
describe('Message Management', function () {
it('NextAccountDetails', function () {
var $scope = {};
var controller = $controller('PatientDefectManagementCtrl', { $scope: $scope });
$scope.Message = 'Hello';
$scope.getNextAccountInfo();
expect($scope.Message).toBe('Hello');
});
});
});

AngularJS : Call controller function from outside with vm

Here I have :
var app = angular.module('app');
app.controller("myController", function () {
var vm = this;
vm.myFunction = function() { alert('foo'); };
});
app.animation('.animate', ["$timeout", function($timeout) {
var vm = this;
return {
addClass: function(element, className, doneFn) {
$timeout(function() {
console.log('this is displayed');
vm.myFunction(); // Doesn't work !
});
}
}
}]);
When I add a class in the template, addClass gets fired. However, vm.myFunction() doesn't, because it does not exist.
How do we do this in angular ?
Some different from yours but I thought this can help you...
in HTML
<div id="outer" ng-controller="myController"></div>
in JS
var app = angular.module('app');
app.controller('myController', function ($scope) {
$scope.myFunction = function() { alert('foo'); };
});
var scope = angular.element($("#outer")).scope();
scope.myFunction();
Modify your code as the following:
var app = angular.module('app');
app.controller('myController', function ($scope) {
var vm = this;
vm.myFunction = function() { alert('foo'); };
$scope = vm;
});
app.animation('.animate', ["$timeout", 'myController', function($timeout, myController) {
var vm = myController;
return {
addClass: function(element, className, doneFn) {
$timeout(function() {
console.log('this is displayed');
vm.myFunction(); // Doesn't work !
});
}
}
}]);

expected scope variable undefined in karma test

I'm having trouble understanding how the scope gets initialized in karma tests. i'm expecting a scope variable to be preset when the test runs, but it keeps coming back as undefined.
What am I missing?
Test Case
describe('loginController', function() {
beforeEach(module('app'));
var $controller, $scope;
beforeEach(inject(function(_$controller_, $rootScope){
$controller = _$controller_;
$scope = $rootScope.$new();
}));
describe('$scope.login', function() {
beforeEach(function() {
controller = $controller('loginController', { $scope: $scope });
});
it('checks it initialized', function() {
expect($scope.foo).toEqual('foo');
expect($scope.bar).toEqual('bar');
//expect($scope).toBeDefined();
//expect($scope.loginData.userName).toEqual('');
//expect($scope.loginData.password).toEqual('');
});
The controller:
angular.module('app').controller('loginController', ['$location',
'authService', function($scope, $location, authService) {
$scope.foo = 'foo';
$scope.bar = 'bar';
$scope.loginData = {
userName: '',
password: ''
};
}]);
I refactored the test code and now it works:
describe('loginController', function() {
beforeEach(module('app'));
var controller, scope;
beforeEach(inject(function($controller, $rootScope){
scope = $rootScope.$new();
console.log('scope1', scope);
controller = $controller('loginController', {
$scope: scope
});
}));
describe('login', function() {
it('sets variables ', function() {
expect(scope).toBeDefined();
expect(scope.loginData).toBeDefined();
expect(scope.loginData.userName).toEqual('');
expect(scope.loginData.password).toEqual('');
});
});
});
try injecting $controller to the function where you instantiate the controller:
beforeEach(inject(function($controller) {
controller = $controller('loginController', { $scope: $scope });
}));

$scopeProvider <- $scope/ Unknown provider

I testing my angular-application with jasmine(http://jasmine.github.io/2.0/) and getting next error:
Unknown provider: $scopeProvider <- $scope
I know, that it's incorrect to build dependency with scope in filters, services, factories, etc., but I use $scope in controller!
Why am i getting this error? controller looks like
testModule.controller('TestCont', ['$filter', '$scope', function($filter, $scope){
var doPrivateShit = function(){
console.log(10);
};
this.lol = function(){
doPrivateShit();
};
this.add = function(a, b){
return a+b;
};
this.upper = function(a){
return $filter('uppercase')(a);
}
$scope.a = this.add(1,2);
$scope.test = 10;
$scope.search = {
};
}]);
and my test's code:
'use strict';
describe('testModule module', function(){
beforeEach(function(){
module('testModule');
});
it('should uppercase correctly', inject(function($controller){
var testCont = $controller('TestCont');
expect(testCont.upper('lol')).toEqual('LOL');
expect(testCont.upper('jumpEr')).toEqual('JUMPER');
expect(testCont.upper('123azaza')).toEqual('123AZAZA');
expect(testCont.upper('111')).toEqual('111');
}));
});
You need to manually pass in a $scope to your controller:
describe('testModule module', function() {
beforeEach(module('testModule'));
describe('test controller', function() {
var scope, testCont;
beforeEach(inject(function($rootScope, $controller) {
scope = $rootScope.$new();
testCont = $controller('TestCont', {$scope: scope});
}));
it('should uppercase correctly', function() {
expect(testCont.upper('lol')).toEqual('LOL');
expect(testCont.upper('jumpEr')).toEqual('JUMPER');
...
});
});
});
Normally, a $scope will be available as an injectable param only when the controller is attached to the DOM.
You need to associate somehow the controller to the DOM (I'm mot familiar with jasmine at all).
I am following a video tutorial from egghead (link bellow) which suggest this approach:
describe("hello world", function () {
var appCtrl;
beforeEach(module("app"))
beforeEach(inject(function ($controller) {
appCtrl = $controller("AppCtrl");
}))
describe("AppCtrl", function () {
it("should have a message of hello", function () {
expect(appCtrl.message).toBe("Hello")
})
})
})
Controller:
var app = angular.module("app", []);
app.controller("AppCtrl", function () {
this.message = "Hello";
});
I am posting it because in the answer selected we are creating a new scope. This means we cannot test the controller's scope vars, no?
link to video tutorial (1min) :
https://egghead.io/lessons/angularjs-testing-a-controller

Categories