I'm having trouble setting up Jasmine tests for an Angular app. Jasmine can't find my controller (I suspect it can't find my app at all).
Here is a sample that demonstrates the problem I'm running into:
angular.module('testMod', [])
.controller('testController', ['$scope', function($scope) {
$scope.person = {name: 'Jim', age: 14};
function innerFunction() {}
}]);
Test:
describe('testMod suite', function() {
var $rootScope, myController;
beforeEach( inject(function($injector) {
angular.module('testMod');
$rootScope = $injector.get('$rootScope');
var $controller = $injector.get('$controller');
myController = $controller('testController', {$scope: $rootScope});
}) );
it('works', function() {
expect( typeof myController.innerFunction).toBe('function');
});
});
It fails on the line
myController = $controller('testController', {$scope: $rootScope});
The error I'm seeing is:
Error: [ng:areq] Argument 'testController' is not a function, got undefined
I'm using the standalone SpecRunner.html for Jasmine, with my app and spec loaded:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Jasmine Spec Runner v2.0.0</title>
<link rel="shortcut icon" type="image/png" href="lib/jasmine-2.0.0/jasmine_favicon.png">
<link rel="stylesheet" type="text/css" href="lib/jasmine-2.0.0/jasmine.css">
<script type="text/javascript" src="lib/jasmine-2.0.0/jasmine.js"></script>
<script type="text/javascript" src="lib/jasmine-2.0.0/jasmine-html.js"></script>
<script type="text/javascript" src="lib/jasmine-2.0.0/boot.js"></script>
<!-- angular-mock must be loaded AFTER Jasmine -->
<script type="text/javascript" src="../src/angular-1.2.5.min.js"></script>
<script type="text/javascript" src="../src/angular-mock-1.2.5.js"></script>
<!-- include source files here... -->
<script type="text/javascript" src="../src/testMod.js"></script>
<!-- include spec files here... -->
<script type="text/javascript" src="spec/testMod.Test.js"></script>
</head>
<body>
</body>
</html>
Any suggestions are appreciated - I've been struggling with this for a while now.
There are several problems with your test:
You are not injecting scope properly.
You are not using scope properly.
There is a toBeDefined() method to check if function is defined no need to type check.
Change the code in your test to
describe('testMod suite', function() {
var $rootScope, testController;
beforeEach(module('testMod'));
beforeEach(inject(function($controller, $rootScope) {
myScope = $rootScope.$new();
ctrl = $controller('testController', {
$scope: myScope
});
}));
it('works', function() {
expect( myScope.innerFunction).toBeDefined();
});
});
Also, change your angular controller code to:
angular.module('testMod', [])
.controller('testController', ['$scope', function($scope) {
$scope.person = {name: 'Jim', age: 14};
$scope.innerFunction = function() {}
}]);
Related
I'm trying to use Angular UI modal, but I keep getting an unknown provider error message: "Error: [$injector:unpr]".
I use custom build to minimize the overall size of the file. I have injected the ui dependency in the app when creating it. The build files are added to the index.html page.
//This is the app.js file
(function() {
angular.module('locatorApp', ['ngRoute', 'ngSanitize', 'ui.bootstrap']);
function config($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'home/home.view.html',
controller: 'homeCtrl',
controllerAs: 'vm'
})
.when('/about', {
templateUrl: '/common/views/genericText.view.html',
controller: 'aboutCtrl',
controllerAs: 'vm'
})
.when('/location/:locationid', {
templateUrl: '/locationDetail/locationDetail.view.html',
controller: 'locationDetailCtrl',
controllerAs: 'vm'
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
}
angular
.module('locatorApp')
.config(['$routeProvider', '$locationProvider', config]);
})();
//This is the controller file
(function() {
angular
.module('locatorApp')
.controller('locationDetailCtrl', locationDetailCtrl);
/*Inject $routeParams service into controller to protect from minification*/
locationDetailCtrl.$inject = ['$routeParams', '$uibModal', 'locatorData'];
function locationDetailCtrl($routeParams, $uibModal, locatorData) {
var vm = this;
vm.locationid = $routeParams.locationid;
locatorData.locationById(vm.locationid)
.success(function(data) {
vm.data = {
location: data
};
vm.pageHeader = {
title: vm.data.location.name
};
})
.error(function(e) {
console.log(e);
});
vm.popupReviewForm = function() {
alert("Let's add a review");
};
}
})();
<!-- This is the index.html file-->
<!DOCTYPE html>
<html ng-app="locatorApp">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LocatoR</title>
<link rel="stylesheet" href="/bootstrap/css/amelia.bootstrap.css">
<link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body ng-view>
<script src="/angular/angular.min.js"></script>
<script src="/lib/angular-route.min.js"></script>
<script src="/lib/angular-sanitize.min.js"></script>
<script src="/lib/ui-bootstrap-custom-2.5.0.min.js"></script>
<script src="/lib/ui-bootstrap-custom-tpls-2.5.0.min.js"></script>
<script src="/angular/locator.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/
jquery.min.js"></script>
<script src="/bootstrap/js/bootstrap.min.js"></script>
<script src="/javascripts/validation.js"></script>
</body>
</html>
//This is the locatorData service
(function() {
/*Data service for pulling data from the API*/
locatorData.$inject = ['$http'];
function locatorData($http) {
var locationByCoords = function(lat, lng) {
return $http.get('/api/locations?lng=' + lng + '&lat=' + lat + '&maxdist=20');
};
var locationById = function(locationid) {
return $http.get('/api/locations/' + locationid);
};
return {
locationByCoords: locationByCoords,
locationById: locationById
};
};
angular
.module('locatorApp')
.service('locatorData', locatorData);
})();
you should use ng-view on a div inside <body>, so script tags will exist after route template is substituted. Then it would be better to reorganize order of script tags you are adding.
At first non-angular script files, then angular, then your sources
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="/javascripts/validation.js"></script>
<script src="/bootstrap/js/bootstrap.min.js"></script>
<script src="/angular/angular.min.js"></script>
<script src="/angular/locator.min.js"></script>
<script src="/lib/angular-route.min.js"></script>
<script src="/lib/angular-sanitize.min.js"></script>
<script src="/lib/ui-bootstrap-custom-2.5.0.min.js"></script>
<script src="/lib/ui-bootstrap-custom-tpls-2.5.0.min.js"></script>
Then use $uibModal service that you've injected:
vm.popupReviewForm = function() {
$uibModal.open({
template: '...html',
//...config from docs
}).then(function(){console.log('closed successfully');})
.catch(function(){console.log('dismissed modal');});
};
Move your script tag either to below of head tag.
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LocatoR</title>
<link rel="stylesheet" href="/bootstrap/css/amelia.bootstrap.css">
<link rel="stylesheet" href="/stylesheets/style.css">
// Scripts
</head>
or, outside the ng-view :
<body>
<div ng-view></div>
// scripts here
</body>
Ok, I've finally figured it out. The problem was using incompatible versions of Angular JS and Angular UI.
Trying to build a simple application that allows a user to upload a file, and upon clicking the 'add' button, It parses the file and displays the result within the browser.
I am using IntelliJ to generate the AngularJS application stub, and modifying it accordingly.
My attempt is below:
view1.html
<!DOCTYPE html>
<html lang="en" ng-app>
<head>
<meta charset="utf-8">
<title>My HTML File</title>
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css">
<link rel="stylesheet" href="../app.css">
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/ng-file-upload/ng-file-upload-shim.js"></script> <!-- for no html5 browsers support -->
<script src="bower_components/ng-file-upload/ng-file-upload.js"></script>
<!--<script src="view1.js"></script>-->
</head>
<body>
<div ng-controller="View1Ctrl">
<input type="file" id="file" name="file"/>
<br/>
<button ng-click="add()">Add</button>
<p>{{data}}</p>
</div>
</body>
</html>
view1.js
'use strict';
angular.module('myApp.view1', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {
templateUrl: 'view1/view1.html',
controller: 'View1Ctrl'
});
}])
.controller('View1Ctrl', ['$scope', function ($scope) {
$scope.data = 'none';
$scope.add = function() {
var f = document.getElementById('file').files[0],
r = new FileReader();
r.onloadend = function(e) {
$scope.data = e.target.result;
}
r.readAsArrayBuffer(f);
}
}]);
view1_test.js
'use strict';
describe('myApp.view1 module', function() {
beforeEach(module('myApp.view1'));
describe('view1 controller', function(){
it('should ....', inject(function($controller, $rootScope) {
//spec body
// var view1Ctrl = $controller('View1Ctrl');
var $scope = $rootScope.$new(),
ctrl = $controller('View1Ctrl', {
$scope: $scope
// $User: {}
});
expect(ctrl).toBeDefined();
}));
});
});
app.js
'use strict';
// Declare app level module which depends on views, and components
angular.module('myApp', [
'ngRoute',
'myApp.view1',
'myApp.view2',
'myApp.version'
]).
config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/view1'});
}]);
I am not sure where I could potentially be going wrong? I viewed quite a few questions to this and tried multiple different approaches but I cannot get this to work despite all of my tests passing.
The issue was around my view1.js file. I found the Papa Parse library extremely useful.
Here is my solution used from the open source Papa Parse community:
Papa.parse(fileInput[0], {
complete: function(results) {
console.log("Complete!", results.data);
$.each(results.data, function(i, el) {
var row = $("<tr/>");
row.append($("<td/>").text(i));
$.each(el, function(j, cell) {
if (cell !== "")
row.append($("<td/>").text(cell));
});
$("#results tbody").append(row);
});
}
});
When i am running SpecRunner.html, I am getting the following error
ReferenceError: module is not defined
My Controller is
angular.module('mymodule', [])
.controller('mycontroller', ['$scope',
function($scope) {
$scope.employees = [{
name: 'Dick',
address: 'Mumbai'
}, {
name: 'Tom',
address: 'US'
}];
$scope.addEmployee = function() {
$scope.employees.push({
name: $scope.name,
address: $scope.address
});
}
}
])
and my spec is
describe('Employee', function() {
var mycontroller, scope;
beforeEach(module('mymodule'));
beforeEach(inject(function($controller, $scope) {
scope = $rootScope;
mycontroller = $controller('mycontroller', {
$scope: scope
});
}));
it("when employee gets added", function() {
var employeecount = $scope.employees.count;
$scope.addEmployee('xxxx', 'yyy');
var employeecount1 = $scope.employees.count;
expect(employeecount + 1).toBe(employeecount1);
});
});
My SpecRunner.html is
<link rel="shortcut icon" type="image/png" href="lib/jasmine-2.2.0/jasmine_favicon.png">
<link rel="stylesheet" href="lib/jasmine-2.2.0/jasmine.css">
<script src="lib/jasmine-2.2.0/jasmine.js"></script>
<script src="lib/jasmine-2.2.0/jasmine-html.js"></script>
<script src="lib/jasmine-2.2.0/boot.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="../Controller.js"></script>
<script src="spec/myspec.js"></script>
PS: Its my first Unit test in jasmine.
Ok so I've been on this issue all day and finally found why it wasn't working even though I had angular mock script in my spec runner. The order matters here, and this is what worked for me.
<link rel="shortcut icon" type="image/png" href="lib/jasmine-2.4.0/jasmine_favicon.png">
<link rel="stylesheet" href="lib/jasmine-2.4.0/jasmine.css">
<script src="lib/jasmine-2.4.0/jasmine.js"></script>
<script src="lib/jasmine-2.4.0/jasmine-html.js"></script>
<script src="lib/jasmine-2.4.0/boot.js"></script>
<script src="../../lib/angular/angular.js"></script>
<script src="../../lib/angular/angular-animate.js"></script>
<script src="../../lib/angular/angular-route.js"></script>
<script src="../../lib/angular/angular-touch.js"></script>
<script src="../../lib/angular/angular-sanitize.js"></script>
<script src="../../lib/angular/angular-mocks.js"></script>
<!-- include source files here... -->
<script src="../student/data/classesData.js"></script>
<!-- include spec files here... -->
<script src="spec/LMSClassesSpec.js"></script>
I really hope this helps someone in the future
You're referencing window.module from the test code. You need to load angular-mocks in your spec-runner to do that, see https://docs.angularjs.org/api/ngMock/function/angular.mock.module
I have an AngularJS app. I would like to implement some end-to-end testing that I can run on-demand. In an effort to do this, I've built a basic test screen with the following:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test Results</title>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/jasmine.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/jasmine-html.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/boot.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular-mocks.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/jasmine.css" />
<!-- Load the Test Files-->
<script type="text/javascript" src="e2e/tests.e2e.js"></script>
</head>
<body>
run tests
</body>
</html>
My tests.e2e.js file looks like the following:
'use strict';
describe('MyApp', function() {
browser.get('http://localhost:11000/index.html');
describe('Welcome Screen', function () {
});
});
When click "run tests" in my test runner, I get an error that says:
MyApp encountered a declaration exception
ReferenceError: browser is not defined
My question is, what am I doing wrong? The examples I've seen use browser to basically start the app. However, I can't seem to figure out how to do end-to-end tests on-demand.
Thank you for any help you can provide.
(function (module) {
var myController = function ($scope, $http) {
$http.get("/api/myData")
.then(function (result) {
$scope.data= result.data;
});
};
module.controller("MyController",
["$scope", "$http", myController]);
}(angular.module("myApp")));
describe("myApp", function () {
beforeEach(module('myApp'));
describe("MyController", function () {
var scope, httpBackend;
beforeEach(inject(function ($rootScope, $controller, $httpBackend, $http) {
scope = $rootScope.$new();
httpBackend = $httpBackend;
httpBackend.when("GET", "/api/myData").respond([{}, {}, {}]);
$controller('MyController', {
$scope: scope,
$http: $http
});
}));
it("should have 3 row", function () {
httpBackend.flush();
expect(scope.data.length).toBe(3);
});
});
});
Initially my controller.js looked like this
function MyCtrl1() {}
MyCtrl1.$inject = [];
function MyCtrl2() {
}
MyCtrl2.$inject = [];
And the html code like this
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="utf-8">
<title>My AngularJS App</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>
<script src="http://angular-ui.github.com/bootstrap/ui-bootstrap-tpls-0.2.0.js"></script>
<link rel="stylesheet" href="css/app.css"/>
</head>
<body>
<ul class="menu">
<li>view1</li>
<li>view2</li>
</ul>
<div ng-view></div>
<div>Angular seed app: v <span app-version></span></div>
<div>Author is : <span app-author></span></div>
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/controllers.js"></script>
<script src="js/filters.js"></script>
<script src="js/directives.js"></script>
</body>
</html>
Here is the service.js code
angular.module('myApp.services', []).
value('version', '0.1')
.value('author','Jay');
And the directive.js code
angular.module('myApp.directives', []).
directive('appVersion', ['version', function(version) {
return function(scope, elm, attrs) {
elm.text(version);
};
}])
.directive('appAuthor', ['author', function(author) {
return function(scope, elm, attrs){
elm.text(author);
};
}]);
The above code worked completely worked fine and displayed version and author configured in service.js
The moment i modify my controller.js to include a new controller as below it stops working and nor the version nor the author is displayed.
The modified controller code is as below
function MyCtrl1() {}
MyCtrl1.$inject = [];
function MyCtrl2() {
}
MyCtrl2.$inject = [];
angular.module('myApp', ['ui.bootstrap']);
var TabsDemoCtrl = function ($scope) {
$scope.panes = [
{ title:"Dynamic Title 1", content:"Dynamic content 1" },
{ title:"Dynamic Title 2", content:"Dynamic content 2" }
];
};
TabsDemoCtrl.$inject = ['$scope'];
Any pointers why this thing is not working.
Looks like your problem is the redeclaration of myApp here:
angular.module('myApp', ['ui.bootstrap']);
I was able to reproduce your problem when I had
angular.module('myApp', ['myApp.services', 'myApp.directives']);
angular.module('myApp', ['ui.bootstrap']);
Switching it to
angular.module('myApp', ['myApp.services', 'myApp.directives', 'ui.bootstrap']);
made everything work again.