Can anyone explain me what's wrong with this code:
.controller('ArticleCreateCtrl', ['$scope', '$state', '$filter', 'Articles', function ($scope, $state, $filter, Articles) {
$scope.article = {};
$scope.save = function(){
$scope.article.categories = $filter('strcstoarray')($scope.article.categories);
Articles.store($scope.article).then(
function(data) {
$scope.article = data;
return $state.transitionTo('articles');
},
function(err) {
throw new Error(err);
}
);
};
}])
In the local machine works well when I run it
in heroku (prodution enviroment therefore with all the js minify)
I get :
Error: assignment to undeclared variable data
UPDATE (My service)
angular.module('mean.system')
.factory('Base',['Restangular', function(Restangular) {
return function(route){
var elements = Restangular.all(route);
return {
one : function (id) {
return Restangular.one(route, id).get();
},
all : function () {
return elements.getList();
},
store : function(data) {
return elements.post(data);
},
copy : function(original) {
return Restangular.copy(original);
},
getElements : function() {
return elements;
}
};
};
}]);
//Articles service used for articles REST endpoint
angular.module('mean.articles').factory('Articles', ['Base', function(Base) {
_.mixin({
'findByCategory': function(collection,category) {
return _.filter(collection, function(item) {
return _.contains(item.categories, category);
});
}
});
function Articles() {
this.findByCategory = function(collection,category){
return _.findByCategory(collection,category);
};
}
return angular.extend(Base('articles'), new Articles());
}]);
Make sure you have uglify configured properly in Gruntfile.js, with mangle: false
uglify: {
options: {
mangle: false
},
production: {
files: '<%= assets.js %>'
}
},
I had the same problem, it's because you must use the ngmin task, which prepares some angular libraries to be minified.
At package.json add the following line before uglify:
"grunt-ngmin": "0.0.3"
Then update dependencies:
npm install
Then at the Gruntfile.js added the ngmin task:
ngmin: {
production: {
files: '<%= assets.js %>'
}
},
Remember to add the ngmin task BEFORE uglify:
grunt.registerTask('default', ['clean','cssmin', 'ngmin','uglify', 'concurrent']);
The next time you'll run the server in production mode your code will work.
Related
I'm trying to test a really simple directive with AngularJS 1.5.5.
The directive itself :
angular.module('whatToPlayWithFriendsApp.card').directive('card', function () {
return {
restrict: 'EA',
link: function link(scope, element, attrs) {
element.bind('click', function () {
angular.element(this).toggleClass('selected');
});
}
};
});
The test:
'use strict';
describe('Directive: card', function () {
// load the directive's module
beforeEach(module('myApp.card'));
var element, scope;
beforeEach(inject(function ($rootScope) {
scope = $rootScope.$new();
}));
it('should make element to have selected class on click', inject(function ($compile) {
element = angular.element('<div card></div>');
$compile(element)(scope);
scope.$digest();
element.triggerHandler('click');
expect(element.hasClass('selected')).toBe(true);
}));
});
But my test fails because of this error :
Undefined is not a constructor (evaluating 'expect(element.hasClass('selected')).toBe(true)')
I looked up at this issue : https://github.com/angular/angular.js/issues/14251
, but I'm using the same version for all angularjs suite. What am I missing here?
Using gulp for the task I run them with : (gulp test:client ):
gulp.task('test:client', ['wiredep:test', 'constant'], (done) => {
new KarmaServer({
configFile: `${__dirname}/${paths.karma}`,
singleRun: true
}, done).start();
});
gulp.task('wiredep:test', () => {
return gulp.src(paths.karma)
.pipe(wiredep({
exclude: [
'/json3/',
'/es5-shim/',
/font-awesome\.css/
],
devDependencies: true
}))
.pipe(gulp.dest('./'));
});
gulp.task('constant', function() {
let sharedConfig = require(`./${serverPath}/config/environment/shared`);
return plugins.ngConstant({
name: 'myApp.constants',
deps: [],
wrap: true,
stream: true,
constants: { appConfig: sharedConfig }
})
.pipe(plugins.rename({
basename: 'app.constant'
}))
.pipe(gulp.dest(`${clientPath}/app/`))
});
Karma files :
// list of files / patterns to load in the browser
files: [
// bower:js
'client/bower_components/jquery/dist/jquery.js',
'client/bower_components/angular/angular.js',
'client/bower_components/angular-resource/angular-resource.js',
'client/bower_components/angular-cookies/angular-cookies.js',
'client/bower_components/angular-sanitize/angular-sanitize.js',
'client/bower_components/lodash/dist/lodash.compat.js',
'client/bower_components/angular-ui-router/release/angular-ui-router.js',
'client/bower_components/semantic/dist/semantic.js',
'client/bower_components/moment/moment.js',
'client/bower_components/angular-moment/angular-moment.js',
'client/bower_components/angular-mocks/angular-mocks.js',
// endbower
'client/app/app.js',
'client/{app,components}/**/*.module.js',
'client/{app,components}/**/*.js',
'client/{app,components}/**/*.{jade,html}'
],
Phantom JS "phantomjs-prebuilt": "^2.1.4"
I'm so used of Jasmine, I didn't realize I was on Chai assertion library.
I have a service that depends on another service from a different module like so:
(function() {
'use strict';
angular
.module('app.core')
.factory('userService', userService);
function authService() {
return: {
userLoggedIn: false
}
}
})();
(function() {
'use strict';
angular
.module('app.services')
.factory('AuthService', authService);
authService.$inject = ['$http', 'userService'];
function authService($http, userService) {
}
I'm trying write tests for my authService but am getting injection errors since it can't find userService
beforeEach(function() {
module('app.services');
});
beforeEach(inject(function(_AuthService_) {
authService = _AuthService_;
}));
How can I overcome this, will using $provide help me here?
UPDATE
I have attempted the following, but still getting the error
beforeEach(function() {
module('app.services');
});
beforeEach(inject(function(_AuthService_, _$provide_) {
authService = _AuthService_;
$provide = _$provide_;
}));
beforeEach(function() {
module(function ($provide) {
$provide.value('userService', function(){
return {
userLoggedIn: false
}
});
});
});
SOLVED
Ok, so I just needed to do the following:
beforeEach(function() {
module('app.dataservices');
module(function ($provide) {
$provide.value('userService', function(){
return {
userLoggedIn: false
}
});
});
});
beforeEach(inject(function(_AuthService_) {
authService = _AuthService_;
}));
Tests are now passing fine for me
Let's say you service uses the $state service and you want to mock id. Specifically the get method. Then you just need to add inside the first describe something like this.
beforeEach(function () {
module(function ($provide) {
$provide.service('$state', function() {
return {
get: function() {}
}
});
});
});
In this gist you can find some interesting examples of mocking services using $provide.
you should be preloading all services in your karma.conf.js (i assume you are using karma).
here is our karma.conf.js file ...
/**
* Karma test runner configuration
*/
'use strict';
module.exports = function (config) {
config.set({
basePath: './',
browsers: ['PhantomJS'],
frameworks: ['jasmine'],
reporters: ['mocha', 'coverage'],
singleRun: true,
preprocessors: {
'src/**/!(*spec)*.js': ['coverage'],
'dest/**/*.html': ['ng-html2js']
},
ngHtml2JsPreprocessor: {
stripPrefix: 'dest/',
moduleName: 'ngHtmlFiles'
},
coverageReporter: {
type: 'html',
dir: 'coverage'
},
files: [
'dest/vendor.min.js',
'bower_components/angular-mocks/angular-mocks.js',
'src/**/*.js',
'dest/**/*.html'
]
});
};
I'm trying to write unit tests for my new Angular App and have troubles. Below is my controller.
'use strict';
angular.module('nileLeApp')
.controller('RegisterController', function ($scope, $translate, $timeout, vcRecaptchaService, Auth, Country, Timezone, RecaptchaService) {
$scope.success = null;
$scope.error = null;
$scope.doNotMatch = null;
$scope.errorUserExists = null;
$scope.registerAccount = {};
$timeout(function () {
angular.element('[ng-model="registerAccount.email"]').focus();
});
$scope.loadCountries = function () {
Country.getCountries()
.then(function (result) {
$scope.countries = result.data;
});
};
$scope.loadTimezones = function () {
Timezone.getTimezones()
.then(function (result) {
$scope.timezones = result.data;
});
};
// ============ Recaptcha specific code START ===============
$scope.recaptcha = {};
$scope.recaptcha.recaptchaResponse = null;
$scope.recaptchaWidgetId = null;
$scope.setResponse = function (response) {
$scope.recaptcha.recaptchaResponse = response;
$scope.recaptchaMissing = false;
};
$scope.setWidgetId = function (widgetId) {
$scope.recaptchaWidgetId = widgetId;
};
$scope.cbExpiration = function () {
$scope.recaptcha.recaptchaResponse = null;
};
// ============ Recaptcha specific code END ===============
$scope.createAccount = function () {
Auth.createAccount($scope.registerAccount).then(function (response) {
$scope.success = true;
}).catch(function (response) {
$scope.success = false;
});
}
$scope.register = function () {
$scope.recaptchaMissing = false;
$scope.recaptchaInvalid = false;
if ($scope.recaptcha.recaptchaResponse != null) {
RecaptchaService.verify($scope.recaptcha).$promise
.then(function (response) {
if (response.data) {
$scope.createAccount();
} else {
$scope.recaptchaInvalid = true;
vcRecaptchaService.reload($scope.recaptchaWidgetId); // Reload captcha
}
}).catch(function (response) {
});
} else {
$scope.recaptchaMissing = true;
}
};
$scope.loadCountries();
$scope.loadTimezones();
});
Below is the test I'm trying.
'use strict';
describe('Register Controllers Tests', function () {
describe('RegisterController', function () {
// actual implementations
var $scope;
var $q;
// mocks
var MockTimeout;
var MockTranslate;
var MockAuth;
var MockCountry;
var MockTimezone;
// local utility function
var createController;
beforeEach(inject(function ($injector) {
$q = $injector.get('$q');
$scope = $injector.get('$rootScope').$new();
MockTimeout = jasmine.createSpy('MockTimeout');
MockAuth = jasmine.createSpyObj('MockAuth', ['createAccount']);
MockCountry = jasmine.createSpyObj('MockCountry', ['getCountries']);
MockTimezone = jasmine.createSpyObj('MockTimezone', ['getTimezones']);
MockTranslate = jasmine.createSpyObj('MockTranslate', ['use']);
var locals = {
'$scope': $scope,
'$translate': MockTranslate,
'$timeout': MockTimeout,
'Auth': MockAuth,
'Country': MockCountry,
'Timezone': MockTimezone
};
createController = function () {
$injector.get('$controller')('RegisterController', locals);
};
}));
it('should load countries on page load', function () {
var mockCountryResponse = [{
'countryId': 1,
'alpha2Code': "AF",
'countryName': "Afghanistan"
}];
MockCountry.getCountries.and.returnValue($q.resolve(mockCountryResponse));
MockTimezone.getTimezones.and.returnValue($q.resolve());
MockAuth.createAccount.and.returnValue($q.resolve());
// given
createController();
$scope.$apply($scope.loadCountries);
expect($scope.countries).toEqual(mockCountryResponse);
});
});
The above expectation doesn't work because $scope.countries is undefined. Following is the error message.
TypeError: 'undefined' is not an object (evaluating 'result.data')
Also, I see the test getting called twice for some strange reason. Below is my Karma configuration file.
// Karma configuration
// http://karma-runner.github.io/0.10/config/configuration-file.html
module.exports = function (config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '../../',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
// bower:js
'main/webapp/bower_components/es5-shim/es5-shim.js',
'main/webapp/bower_components/jquery/dist/jquery.js',
'main/webapp/bower_components/angular/angular.js',
'main/webapp/bower_components/angular-animate/angular-animate.js',
'main/webapp/bower_components/angular-aria/angular-aria.js',
'main/webapp/bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
'main/webapp/bower_components/bootstrap/dist/js/bootstrap.js',
'main/webapp/bower_components/angular-bootstrap-nav-tree/dist/abn_tree_directive.js',
'main/webapp/bower_components/angular-file-upload/angular-file-upload.js',
'main/webapp/bower_components/angular-messages/angular-messages.js',
'main/webapp/bower_components/skycons/skycons.js',
'main/webapp/bower_components/angular-skycons/angular-skycons.js',
'main/webapp/bower_components/angular-smart-table/dist/smart-table.min.js',
'main/webapp/bower_components/angular-touch/angular-touch.js',
'main/webapp/bower_components/angular-cache-buster/angular-cache-buster.js',
'main/webapp/bower_components/angular-cookies/angular-cookies.js',
'main/webapp/bower_components/angular-dynamic-locale/src/tmhDynamicLocale.js',
'main/webapp/bower_components/angular-local-storage/dist/angular-local-storage.js',
'main/webapp/bower_components/angular-loading-bar/build/loading-bar.js',
'main/webapp/bower_components/angular-resource/angular-resource.js',
'main/webapp/bower_components/angular-sanitize/angular-sanitize.js',
'main/webapp/bower_components/angular-translate/angular-translate.js',
'main/webapp/bower_components/messageformat/messageformat.js',
'main/webapp/bower_components/angular-translate-interpolation-messageformat/angular-translate-interpolation-messageformat.js',
'main/webapp/bower_components/angular-translate-loader-partial/angular-translate-loader-partial.js',
'main/webapp/bower_components/angular-translate-loader-static-files/angular-translate-loader-static-files.js',
'main/webapp/bower_components/angular-translate-storage-cookie/angular-translate-storage-cookie.js',
'main/webapp/bower_components/angular-translate-storage-local/angular-translate-storage-local.js',
'main/webapp/bower_components/angular-ui-router/release/angular-ui-router.js',
'main/webapp/bower_components/moment/moment.js',
'main/webapp/bower_components/fullcalendar/dist/fullcalendar.js',
'main/webapp/bower_components/angular-ui-calendar/src/calendar.js',
'main/webapp/bower_components/angular-ui-grid/ui-grid.js',
'main/webapp/bower_components/angular-ui-select/dist/select.js',
'main/webapp/bower_components/angular-ui-utils/ui-utils.js',
'main/webapp/bower_components/angular-xeditable/dist/js/xeditable.js',
'main/webapp/bower_components/angularjs-toaster/toaster.js',
'main/webapp/bower_components/angular-strap/dist/angular-strap.js',
'main/webapp/bower_components/angular-strap/dist/angular-strap.tpl.js',
'main/webapp/bower_components/angular-recaptcha/release/angular-recaptcha.js',
'main/webapp/bower_components/bootstrap-daterangepicker/daterangepicker.js',
'main/webapp/bower_components/bootstrap-filestyle/src/bootstrap-filestyle.js',
'main/webapp/bower_components/bootstrap-slider/bootstrap-slider.js',
'main/webapp/bower_components/bootstrap-tagsinput/dist/bootstrap-tagsinput.js',
'main/webapp/bower_components/bootstrap-wysiwyg/bootstrap-wysiwyg.js',
'main/webapp/bower_components/bower-jvectormap/jquery-jvectormap-1.2.2.min.js',
'main/webapp/bower_components/datatables/media/js/jquery.dataTables.js',
'main/webapp/bower_components/flot/jquery.flot.js',
'main/webapp/bower_components/flot-spline/js/jquery.flot.spline.js',
'main/webapp/bower_components/flot.tooltip/js/jquery.flot.tooltip.js',
'main/webapp/bower_components/footable/js/footable.js',
'main/webapp/bower_components/html5sortable/jquery.sortable.js',
'main/webapp/bower_components/json3/lib/json3.js',
'main/webapp/bower_components/ng-grid/build/ng-grid.js',
'main/webapp/bower_components/intl-tel-input/build/js/intlTelInput.min.js',
'main/webapp/bower_components/intl-tel-input/lib/libphonenumber/build/utils.js',
'main/webapp/bower_components/ng-intl-tel-input/dist/ng-intl-tel-input.js',
'main/webapp/bower_components/ngImgCrop/compile/minified/ng-img-crop.js',
'main/webapp/bower_components/ngstorage/ngStorage.js',
'main/webapp/bower_components/ng-file-upload/ng-file-upload.js',
'main/webapp/bower_components/ngInfiniteScroll/build/ng-infinite-scroll.js',
'main/webapp/bower_components/oclazyload/dist/ocLazyLoad.min.js',
'main/webapp/bower_components/screenfull/dist/screenfull.js',
'main/webapp/bower_components/slimscroll/jquery.slimscroll.min.js',
'main/webapp/bower_components/textAngular/dist/textAngular.min.js',
'main/webapp/bower_components/venturocket-angular-slider/build/angular-slider.js',
'main/webapp/bower_components/videogular/videogular.js',
'main/webapp/bower_components/videogular-buffering/buffering.js',
'main/webapp/bower_components/videogular-controls/controls.js',
'main/webapp/bower_components/videogular-ima-ads/ima-ads.js',
'main/webapp/bower_components/videogular-overlay-play/overlay-play.js',
'main/webapp/bower_components/videogular-poster/poster.js',
'main/webapp/bower_components/waves/dist/waves.min.js',
'main/webapp/bower_components/angular-mocks/angular-mocks.js',
// endbower
'main/webapp/scripts/app/app.js',
'main/webapp/scripts/app/**/*.+(js|html)',
'main/webapp/scripts/components/**/*.+(js|html)',
'test/javascript/spec/helpers/module.js',
'test/javascript/spec/helpers/httpBackend.js',
'test/javascript/**/!(karma.conf|protractor.conf).js'
],
// list of files / patterns to exclude
exclude: ['test/javascript/e2e/**'],
preprocessors: {
'./main/webapp/scripts/**/*.js': ['coverage'],
'**/*.html': ['ng-html2js']
},
reporters: ['dots', 'jenkins', 'coverage', 'progress'],
jenkinsReporter: {
outputFile: '../build/test-results/karma/TESTS-results.xml'
},
coverageReporter: {
dir: '../build/test-results/coverage',
reporters: [
{type: 'lcov', subdir: 'report-lcov'}
]
},
// web server port
port: 9876,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: true,
// to avoid DISCONNECTED messages when connecting to slow virtual machines
browserDisconnectTimeout : 10000, // default 2000
browserDisconnectTolerance : 1, // default 0
browserNoActivityTimeout : 4*60*1000 //default 10000
});
};
I'm stuck on writing unit test for last couple days as I find them quite confusing and not simple like in Java. Will appreciate any help.
The above expectation doesn't work because $scope.countries is undefined
^^ That's not true. It's not that $scope.countries is undefined, it's that result is undefined, and it's not the result you're trying to assign to $scope.countries, it's the one relating to $scope.timezones
I think this is your problem here:
MockTimezone.getTimezones.and.returnValue($q.resolve());
You're implicitly passing undefined into that resolve() function, and THAT'S throwing an error when you instantiate your controller.
It's throwing that error because you've got this line at the end of your controller:
$scope.loadTimezones();
It's for this reason that I stopped initializing controllers within themselves. Now I do it using ng-init, initiated from the HTML. If you make the same change as I did you won't encounter issues like this again in the future.
In my AngularJS app, using Yeoman, when minifying my app I have this error :
Uncaught Error: [$injector:unpr] Unknown provider: aProvider <- a <- $http <- AuthenticationService
that I obviously do not have before minifying.
Here is the definition of my service in a separate runner.js file :
angular.module('myApp').run(['$rootScope', 'AuthenticationService', 'FlashService', 'SessionService', function ($rootScope, AuthenticationService, FlashService, SessionService) {
//some code
}]);
I thought of course about the typical Injection error when minifying but I am struggling to see what is wrong in my code...
UPDATE
My AutenticationService :
angular.module('myApp').factory("AuthenticationService", ['$http', '$rootScope', '$sanitize', 'SessionService', 'FlashService', 'SETTINGS', function($http, $rootScope, $sanitize, SessionService, FlashService, SETTINGS) {
var cacheSession = function() {
SessionService.set('authenticated', true);
};
var uncacheSession = function() {
SessionService.unset('authenticated');
SessionService.unset('user');
};
var loginError = function(response) {
FlashService.show('warning', response.flash);
};
var loginSuccess = function(response) {
SessionService.set('user', JSON.stringify(response));
FlashService.clear();
};
var logoutSuccess = function(response) {
FlashService.show('success', response.flash);
};
var sanitizeCredentials = function(credentials) {
return {
email: $sanitize(credentials.email),
password: $sanitize(credentials.password)
};
};
return {
login: function(credentials) {
var login = $http.post(SETTINGS.urlBackend+"/auth/login", sanitizeCredentials(credentials));
login.success(cacheSession);
login.success(loginSuccess);
login.error(loginError);
return login;
},
logout: function() {
var logout = $http.get(SETTINGS.urlBackend+"/auth/logout");
logout.success(uncacheSession);
logout.success(logoutSuccess);
logout.error(loginError);
return logout;
},
isLoggedIn: function() {
var checked = $http.get(SETTINGS.urlBackend+"/auth/check");
return (checked && SessionService.get('authenticated'));
}
};
}]);
Try setting mangle: false in the Uglify configuration in your Gruntfile.js:
grunt.initConfig({
// ...
uglify: {
options: {
mangle: false
}
}
});
I've had this happen when using certain packages from Bower. I believe some of the Angular UI suite of tools weren't compatible, for some reason.
I highly recommend an alternative approach to manually setting up the angular minification work around - the wrapping of the "module" - controller, service, factory - in the [] brackets.
Use the ng-min module! It's written by the guys as Angular - namely Brian Ford. But most important it removes this complication in writing Angular modules, they become clean and readable again and the ng-min does the hard work of fixing minification issues.
I know it's not an answer to you question, but it might be a solution to the problem you are facing in general.
// Allow the use of non-minsafe AngularJS files. Automatically makes it // minsafe compatible so Uglify does not destroy the ng references
ngmin: {
dist: {
files: [
{
expand: true,
cwd: '.tmp/concat/scripts',
src: '*.js',
dest: '.tmp/concat/scripts'
}
]
}
},
My jasmine test (using karma) throws the error : Argument 'salesListController' is not a function, got undefined
After searching a lot this question seems close to my error, but this is unit test not e2e scenario test.
My test-main.js
(function (window, require) {
'use strict';
var file, requireModules;
requireModules = [];
for (file in window.__karma__.files) {
if (window.__karma__.files.hasOwnProperty(file)) {
// console.log('loaded file'+ file);
if (file.substring(file.length - 26, file.length) === 'salesListControllertest.js') {
console.log('Added file to testing..');
requireModules.push(file);
}
}
}
//requireModules.push('appModule');
//requireModules.push('mocks');
deps: requireModules,
require({
baseUrl: '',
paths:{
'angular': '/base/app/bower_components/angular/angular',
'angularResource': '/base/app/bower_components/angular-resource/angular-resource',
'angularMocks': '/base/app/bower_components/angular-mocks/angular-mocks',
'appModule': '/base/app/scripts/appModule',
'appRoutes':'/base/app/scripts/appRoutes',
'services/dependencyResolverFor':'/base/app/scripts/services/dependencyResolverFor',
'salesListController' : '/base/app/scripts/controllers/salesListController'
},
shim:{
'angular' :{
exports:'angular'
},
'appRoutes': {exports:'appRoutes'},
'services/dependencyResolverFor' : {exports:'services/dependencyResolverFor'},
'appModule': {
deps: ['appRoutes', 'services/dependencyResolverFor'],
exports: 'appModule'
},
'angularResource': {
deps: ['angular'],
exports: 'angularResource'
},
'angularMocks': {
deps: ['angularResource'],
exports: 'angularMocks'
} ,
'salesListController': {
deps: ['appModule'],
exports: 'salesListController'
}
}
}, requireModules, function () {
window.__karma__.start();
}, function (err) {
var failedModules = err.requireModules;
console.log("err", err);
if (failedModules && failedModules[0]) {
throw new Error("Module could not be loaded: " + failedModules);
} else {
throw new Error("unknown error:" + err);
}
}); }(window, require));
My example.spec
define(['appModule','angular', 'angularResource', 'angularMocks','salesListController'],
function(app, angular, angularResource, angularMocks, saleslstCtrl) {
describe('SalesListController1', function(){
beforeEach(module('AngularSampleBhoomiApp'));
var SalesListController, scope;
var sales = [{Customer:"A1",Number:1,Id:1},{Customer:"B1",Number:2,Id:2}];
beforeEach(inject(function($controller, $rootScope,$injector){
scope = $rootScope.$new();
SalesListController = $controller('salesListController', {$scope:scope, getAllSalesResolved:sales});
}));
it('should have 0 items when loaded', function(){
expect(scope.sales).toBeUndefined();
});
});});
My example controller
define(['appModule'], function(myApp){
function SalesLstCtrl(){
myApp.lazy.controller('salesListController' ,['$scope', 'getAllSalesResolved',
function ($scope, sales) {
console.log('before sales');
$scope.sales= sales;
console.log( $scope.sales.length);
}]); }
return SalesLstCtrl;});
Since I am using lazy loading I am resolving the dependencies like this :
define([], function()
{
return function(dependencies)
{
var definition =
{
resolver: ['$q','$rootScope', function($q, $rootScope)
{
var deferred = $q.defer();
require(dependencies, function()
{
$rootScope.$apply(function()
{
deferred.resolve();
});
});
return deferred.promise;
}]
}
return definition;
} });
My github repo with the entire sample is here
Pl help.
Yes, I have found the solution.
Here is my blog post for the same.
GitHub code is here : sample
It is done through mocking the module creation.
Edit :
With code. The trick here is to initialize AngularJS like this :
define(function(){ var app = angular.module('AngularAppModule', 'ngResource']);app.lazy = app; return app;});
This will add app.lazy reference in Angular, and then RequireJS can initialize the controllers the same way. Test-main.js file is the same. For running Karma, test-main will load all the scripts upfront and Require will not be intrusive. Let me know if you have further questions.