Error while Creating Angular JS Jasmine Test Case - javascript

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');
});
});
});

Related

karma test controller using toBeDefined failed

My test failed because it says my controller is not defined. So strange I think I did everything right.
describe('homeCtrl', function() {
var httpBackend, controller, scope;
beforeEach(module('App'));
beforeEach(inject(function($httpBackend, $controller) {
scope = {};
httpBackend = $httpBackend;
controller = $controller('homeCtrl', { $scope: scope });
}));
it('should exist', function() {
expect(controller).toBeDefined();
});
});
and I have my home.js which is the controller like this
var App = angular.module('App')
App.controller('homeCtrl', function($scope) {
})
The error is Expected undefined to be defined.
Your home.js should have dependencies injected in module, change it as,
var App = angular.module('App',[])
App.controller('homeCtrl', function($scope) {
})

AngularJS: TypeError: undefined is not an object for localstorage

I want to test the values in localstorage. Here is the package I use to store those values: https://www.npmjs.com/package/ngstorage
Here is my code:
var module = angular.module(‘myModule', ['ngStorage']);
module.controller(‘MyController’, ['$scope', '$localStorage', function($scope,$localStorage){
$scope.storage = $localStorage;
$scope.data = {
name: “55 Cherry St.“
};
$scope.storage.name = $scope.data.name;
}]);
I want to test the above code in Jasmine and Mocha. I dont know how I can as it gives me this error now:
TypeError: undefined is not an object (evaluating 'expect($localStorage).to.be') (line 14)
Here is my test code:
describe('my Module', function () {
var $controller;
var $scope;
var element;
beforeEach(module('myModule'));
beforeEach(module('ngStorage'));
beforeEach(function() {
$scope = {};
inject(function ($controller, $rootScope, $compile, $localStorage) {
var $controller = $controller('myController', {$scope: $scope});
});
});
describe('My controller', function () {
it('should contain a $localStorage service', inject(function(
$localStorage
) {
expect($localStorage).not.to.equal(null);
}));
});
});
Jasmine doesn't have a expect('something').not.to.equal() function. Use this instead:
expect($localStorage).not.toBe(null);
Also, while reproducing your error, myController is not defined. Fixed using:
var $controller = $controller('MyController', {$scope: $scope}); // MyController (uppercase)
And I think beforeEach(module('ngStorage')); is not necessary, since it already is a dependency of your module.
You have to add a variable for it in order to test it.Below is the improvement you need to do in your code
describe('my Module', function () {
var $controller;
var $scope;
var element;
var $localStorage;
beforeEach(module('myModule'));
beforeEach(module('ngStorage'));
beforeEach(function() {
$scope = {};
inject(function ($controller, $rootScope, $compile, $localStorage) {
var $controller = $controller('myController', {$scope: $scope, $localStorage: $localStorage});
});
});
describe('My controller', function () {
it('should contain a $localStorage service', inject(function(
$localStorage
) {
expect($localStorage).not.to.equal(null);
}));
});
});
OR
expect(controller.$localStorage).not.to.equal(null); //$localStorage is part of controller now

Not a function (mocking error?)

I'm trying to do some unit testing on my Ionic app, using the Karma-jasmine framework, and it's giving me quite the headache. I have a function in my controller I want to test by giving it some dummy input (the credentials), but I keep getting the errors
TypeError: 'undefined' is not a function (evaluating '$controller')
TypeError: 'undefined' is not an object (evaluating '$scope.credentials.username = "uname"')
I've tried some alternate ways to do this, but one of them kept giving me some bogus that I needed to add dependencies from my services.js as well (i.e. $ionicPopup), which might have some truth to it, but I'm super new to all of this. Any help would be greatly appreciated.
I've made a lot of progress by mostly rewriting this, but I'm now getting the error
TypeError: 'undefined' is not a function (evaluating 'LoginService.initiateRequest(
$scope.credentials.username,
$scope.credentials.password)')
at c:/Users/name/git/mobile/www/js/controllers.js:18
It's saying that it's not a function in my controllers.js file...which it DEFINITELY is. Really not understanding this one. Is it something to do with services?
I have here my controllers.tests.js file...
describe('Controllers', function() {
beforeEach(module('myApp.services', 'myApp.controllers'));
var mockRequest = {
}
beforeEach(function() {
module(function($provide) {
$provide.value('initiateRequest', mockRequest);
});
});
var $rootScope, $controller, $sharedProperties, $resource;
beforeEach(inject(function(_$controller_, $rootScope) {
myScope = $rootScope.$new();
$scope = {};
$state = {};
LoginService = {};
localStorageService = {};
sharedProperties = {};
$ionicLoading = myScope;
initiateRequest = mockRequest;
$controller = _$controller_;
}));
describe('$scope.login()', function() {
it('does something', function() {
var $scope = {};
var controller = $controller('LoginController', {
$scope: $scope,
$state: $state,
LoginService: LoginService,
localStorageService: localStorageService,
sharedProperties: sharedProperties,
$ionicLoading: $ionicLoading
});
expect($scope.login).toBeDefined(true);
expect($scope.show).toBeDefined(true);
$scope.login();
});
});
});
describe('Controllers', function () {
beforeEach(module('myApp.services', 'myApp.controllers'));
var mockRequest = {};
beforeEach(function () {
module(function ($provide) {
$provide.value('initiateRequest', mockRequest);
});
});
var $controller, sharedProperties, state, scope, ionicLoading, LoginService, localStorageService, initiateRequest;
beforeEach(function () {
inject(function ($rootScope, _$controller_) {
scope = $rootScope.$new();
$controller = _$controller_;
ionicLoading = {};
sharedProperties = {};
LoginService = {};
localStorageService = {};
initiateRequest = mockRequest;
});
});
describe('$scope.login()', function () {
beforeEach(function () {
$controller('LoginController', {
$scope: scope,
$state: state,
LoginService: LoginService,
localStorageService: localStorageService,
sharedProperties: sharedProperties,
$ionicLoading: ionicLoading
});
scope.$apply();
});
it('does something', function () {
expect(scope.login).toBeDefined();
expect(scope.show).toBeDefined();
});
});
});

Call a controller function from Karma and Jasmine testing

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.

Unit testing in AngularJS with mock $resource

Trying to get some units tests in AngularJS (using jasmine & karma) working and struggling to comprehend dependency injection... current error message in karma reads 'Error: Argument 'fn' is not a function, got string'
app.js
angular.module('App', [ 'App.Services', 'App.Controllers', 'App.Directives']);
controller.js
angular.module('App.Controllers', []).
controller('MarketplaceCtrl', function ($scope, apiCall) {
apiCall.query({
type: 'engagement',
engagement_status__in: '0,1'
}, function(data) {
var engagements = {};
$.each(data.objects, function (i, engagement) {
engagements[engagement.lawyer_id] = engagement
});
$scope.engagements = engagements;
});
});
services.js
angular.module('App.Services', ['ngResource']).
factory('apiCall', function ($resource) {
return $resource('/api/v1/:type',
{type: '#type'},
{
query: {
method: 'GET',
isArray: false
}
}
);
});
controllerSpec.js
describe('controllers', function () {
beforeEach(
module('App', ['App.Controllers', 'App.Directives', 'App.Services'])
);
describe('MarketplaceCtrl', function () {
var scope, ctrl, $httpBackend;
beforeEach(inject(function (_$httpBackend_, $rootScope, $controller) {
$httpBackend = _$httpBackend_;
$httpBackend.expectGET('/api/v1/engagement?engagement_status__in=0,1').
respond([]);
scope = $rootScope.$new();
/* Why is MarketplaceCtrl not working? :( */
ctrl = $controller('MarketplaceCtrl', {$scope: scope});
}));
it('should have a MarketplaceCtrl controller', (function () {
expect(ctrl).not.to.equal(null);
}));
});
});
Ended up using this example https://github.com/tebriel/angular-seed/commit/b653ce8e642ebd3e2978d5404db81897edc88bcb#commitcomment-3416223
Basically:
describe('controllers', function(){
beforeEach(module('myApp.controllers'));
it('should ....', inject(function($controller) {
//spec body
var myCtrl1 = $controller('MyCtrl1');
expect(myCtrl1).toBeDefined();
}));
it('should ....', inject(function($controller) {
//spec body
var myCtrl2 = $controller('MyCtrl2');
expect(myCtrl2).toBeDefined();
}));
});

Categories