setting up ng-htmljs-preprocessor karma preprocessor - angularjs

I am setting up my Karma configuration file, but I do not fully understand some of options that exist as I am not having success testing templates that have ran through the ngHtml2JsPreprocessor and have been
$templateCached
Inside of the ngHtml2JsPreprocessor I can add a few key value properties involving paths.
ngHtml2JsPreprocessor: {
stripPrefix: ".*/Went all the way back to the root of my application/",
// moduleName: 'templatesCached'//
},
I commented out the templates for now to make sure that I am getting access to each file as module. I am loading the modules with no error. I can find the templateCached version in my dev tools.
beforeEach(module('template'));
My Templates folder sits outside the basepath I created.
basePath: 'Scripts/',
I have it referenced inside the preprocessors object
preprocessors: {
'../Templates/**/*.html' : ['ng-html2js']
},
Again all of my templates are now js files and cached.
I inside of my package.json I saved the files as
save-dev
"karma-chrome-launcher": "^0.2.2",
"karma-jasmine": "^0.2.2",
"karma-ng-html2js-preprocessor": "^0.2.1",
I referenced my installs in the plugins.
plugins: [
'karma-chrome-launcher',
'karma-jasmine',
'karma-sinon',
'karma-ng-html2js-preprocessor'
],
I have all of my files loaded
files: [
//jquery libaries
// angular libraries
// Scripts files
// source app.js
// tests folder and files
]
My tests are running off of Karma start
However, my directive is just an empty string
element.html()
returns ""
I have bard inject set up
bard.inject(
"$compile",
"$controller",
"$rootScope",
'$templateCache',
"haConfig",
"$q"
);
Here is the inside of my beforeEach
bard.mockService(haConfig, {
getTemplateUrl: '/tst!'
});
//bard.mockService(haConfig, {});
console.log('ha config2', haConfig.getTemplateUrl());
var html = angular.element("<div explore-hero></div>");
console.log('htl',haConfig.getTemplateUrl());
scope = $rootScope.$new();
//templateCache
element = $compile(html)(scope);
//console.log(haConfig.getTemplateUrl(html));
scope.$digest(element);
console.log('missing text',haConfig.getTemplateUrl(html));
controller = element.scope();
console.log("element", element);
I have no idea why I am getting an empty string back. I am creating the html file but, nothing is inside of it.
All I can wonder if I should have the the templatesCached files showing up in a folder on my dev tools? Also whether or not the files should be referenced inside of the files array inside karma.conf.js
Right now I have the html files referenced? I have tried the js files but that did not seem to do anything

The problem was actually quite simple fix. I was tempted to delete it but, in case someone has a similar issue I want this to be available.
Inside the karma.conf.js I have a
stripPrefix: 'rootDirectory' // was already in place
stripSuffix: '.js.html' // I had to make a strip on the templatesCached
prependSuffix: '.html' // this is what I was searching for
When the preprocessor ran it templateCached all of my files. However, they did not end the way that I was expecting them and I could not read them. I had the module and other parts set up correctly.

Related

What does "packages" property of requireJs config mean ? And how it works?

I am trying to understand how requireJs works. There is a property "packages" which I came across while configuring requireJs. What my understanding is that 'packages' is used to mention a complete folder/module which contains "main.js" & main.js requires all other dependencies inside that module. But does mentioning "packages" in config file will automatically load main.js or do we need to do something to make it load main.js ?
Below is my folder structure & main.js snippet. 'main.js' is the data-main or entry point of application.
So after trying few stuff, what I understood is that packages lets you mention a directory or folder which has other modules (commonJs directory is what docs refer it to). So the way we define a package is :
packages: [
{name : 'controllers' , location :'../controllers' },
{name : 'directives' , location : '../directives'},
{name : 'services' , location : '../services'}
] ,
Where name is an alias for this entire directory or folder. location is the path of the folder relative to your main.js or requireJs's config file.
Now answering the 2) point - it does not load automatically. For it to load we need to require it somewhere. Once we require it, requireJs will first load the main.js inside that directory by default. And we need to define all the other modules inside that directory, in this main.js. For eg- I will require it in my app.js before bootstrapping my application-
require([
// Add additional dependencies
'angular',
'angular-ui-router',
'jquery',
'app',
'route',
"controllers",
"directives",
"services"] , function(){ console.log("All dependencies loaded"); });

JSHint in WebStorm doesn't know protractor command "browser"

I'm trying to make test for AngularJS web page in WebStorm (using Jasmine and Protractor frameworks), I'm using JHint for code inspection...
All code is OK except one command: "browser", example of code:
describe('Test',function(){
it('Open page',function(){
browser.get('https://www.angularjs.org');
browser.sleep(2000);
});
});
JSHint is still highlighting errors with browser:
Problem synopsis JSHint: 'browser' is not defined. (W117)
Unresolved function or method sleep() at line 20
In JHint Environment I have enabled:
Jasmine
Node.js
In JavaScript Libraries I have enabled:
Node.js Core
angular-protractor-DefinitelyTyped
jasmine-DefinitelyTyped
selenium-webdriver-DefinitelyTyped
Does anybody know what do I have to enable or which Library do I have to download to make JSHint understand the "browser" command please?
Do you have a .jshintrc file ?
{
"globals": {
"browser": false,
},
"jasmine": true
}
You can add browser as a global.
JSHint works on per-file basis and doesn't 'see' global variables defined in other files unless they are added to 'global' list. This can be done by either adding the corresponding comments (/* global browser*/) to your files - see http://www.jshint.com/docs/, or by adding variables/functions you'd like to use globally to the 'Predefined' list in WebStorm Preferences -> Languages & Frameworks -> Javascript -> Code Quality Tool -> JSHint -> Predefined (,separated).

karma.conf.js automatic file ordering?

I have a large angularjs project ordered by features. I'd like to setup unit testing but I'm having trouble getting the karma.conf.js file ordering setup.
I tried specifying a simple glob pattern like **/*.js but many of my modules failed to load due to the ordering that they're included in Karma when ran. As I understand, it's alphabetical, first match.
I was able to resolve this by manually figuring out the ordering by doing something like this:
// list of files / patterns to load in the browser
files: [
// External scripts
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-cookies/angular-cookies.js',
'bower_components/angular-resource/angular-resource.js',
'bower_components/angular-route/angular-route.js',
// NOTE: ORDER IS IMPORTANT
// Modules: load module first, then all controllers, services, etc
'scripts/module1/module1.js',
'scripts/module1/**/*.js',
'scripts/module2/module2.js',
'scripts/module2/**/*.js',
// Load overall app module last
'scripts/app.js',
// Load mocks and tests
'test/mock/**/*.js',
'test/spec/**/*.js'
],
This seems like it will be cumbersome to maintain over time as new modules are added. Is there a way to automatically resolve the ordering?
Note: One possible solution I was thinking was to concat all the files together but I googled to see if others are doing this and found no examples.
I think you may look into different solutions here, depending on how you want to manage your project.
Solution n.1
Use AMD/RequireJS: do not load your modules all at once but just require them when you need.
Sometimes it may not fit your needs tough making the project over complicated, so look below.
Note: this is IMHO the most elegant solution and karma does support requireJS.
Solution n.2
Create a namespace where you append all your stuff and start them when the DOM is ready (usually pretty quick, but it really depends on how much scripts you load)
// module A
// Something like this should be fine
(function(){
window.MyNamespace = window.MyNamespace || {};
// append things to the namespace...
})();
// module B
(function(){
window.MyNamespace = window.MyNamespace || {};
// append things to the namespace...
})();
// This is very rough but it should give the idea
window.ondomready = MyNamespace.start;
Note: while this may work you have to fiddle a bit with your project to change the structure accordingly.
I would go for the one above unless you really hates requireJS and all the modules stuff.
Solution n.3
Programmatically order your Karma files: I wrote about it in this answer here.
Note: this is the less mantainable of the options.
If this
// Modules: load module first, then all controllers, services, etc
'scripts/module1/module1.js',
'scripts/module1/**/*.js',
'scripts/module2/module2.js',
'scripts/module2/**/*.js',
could instead force the same filenaming convention on the module-declaration file, to be this
// Modules: load module first, then all controllers, services, etc
'scripts/module1/moduleDeclaration.js',
'scripts/module1/**/*.js',
'scripts/module2/moduleDeclaration.js',
'scripts/module2/**/*.js',
Then you could do this
// Modules: load module first, then all controllers, services, etc
'scripts/**/moduleDeclaration.js',
'scripts/**/*.js',
I do something similar, though I do break out interfaces & types between moduleDeclaration and "the rest of it".
I use browserify and i have no prblems with it, here is my configuration:
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['browserify', 'jasmine'],
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'dev/**/*Spec.js'
],
exclude: [
],
browserify: {
watch: false,
debug: true
},
preprocessors: {
'dev/**/*Spec.js': ['browserify']
},
reporters: ['progress'],
port: ****,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['Chrome'],
singleRun: true
});
};

Render all Jade files in large Express application using folder structure?

How can I configure Express to render all Jade files regardless of path? The application I'm on is large with a very complex structure. I'm successfully serving static files however I need many of them to be rendered. We are using Jade for all files needing markup.
I'm worried that the pattern below will force me to create a route alias for every folder that has a Jade file... which would be bad. I would like to tell Express to simply render everything with a .jade extension... OR... allow me to create a route PREFIX for the root that would cause a Render operation instead of Static.
client
app
services
modules
moduleA
itemA
itemAList.jade
itemAList.js
itemADetails.jade
itemADetails.js
itemB
itemBList.jade
itemBList.js
itemBDetails.jade
itemBDetails.js
moduleB
itemC
itemCList.jade
itemCList.js
itemCDetails.jade
itemCDetails.js
itemD
itemDList.jade
itemDList.js
itemDDetails.jade
itemDDetails.js
assets
js
css
server
config
views
Routes.Config.js
module.exports = function(app){
app.get('/*', function(req, res){
res.render('../../client/' + req.params[0]);
});
app.get('/', function(req, res){
res.render('../../client/index', {});
})
}
Express.Config.js
[snip]
app.use(express.static(path.join(constants.rootPath, '/client')));
I would use a Grunt file watcher to kick off a compile any time your .jade files are created or saved. By using the Gruntfile.js below, you can issue the command grunt watch and have this automagically occur in the background:
module.exports = function(grunt){
grunt.initConfig({
jade: {
compile: {
options: {
client: false,
pretty: true
},
files: [{
cwd: "client/app/templates",
src: "**/*.jade",
dest: "client/app/modules",
ext: ".html",
expand: true
}]
}
},
watch: {
html: {
files: 'client/app/templates/**/*.jade',
tasks: ['jade'],
options: {
atBegin: true,
interrupt: true
}
}
}
});
grunt.loadNpmTasks("grunt-contrib-jade");
grunt.loadNpmTasks("grunt-contrib-watch");
grunt.registerTask('default', ['jade']);
}
Now, this assumes that you will create a "templates" folder parallel to the "modules" folder and put all of your .jade files there in the structure you want. You may then add your controllers and other .js files to the modules folder structure as normal.
I'm not sure how Grunt will behave with the source and destination both pointing to the same folder. However, if you REALLY want to keep your .jade and .html files in the same folder, or if you don't want to create a "templates" structure, you SHOULD be able to simply change the cwd variable to point to the "modules" folder:
files: [{
cwd: "client/app/modules", // templates folder removed
src: "**/*.jade",
dest: "client/app/modules",
ext: ".html",
expand: true
}]
NOTE:
Sounds like you've misunderstood some of the fundamentals. From what I'm learning, within a typical MEAN application, there is generally a folder structure that is meant to be purely static. In your example, this would be your "client" folder. By specifying special routes, you individually decide how every other case is handled. The example above is meant to accomplish what I think you're asking while still maintaining the purpose of the "static" area.
UPDATE: Don't use same folder!
I went back and tried using the same folder for the source and destination. This caused Grunt to hang without any way to break out of it. This hang does NOT occur when they are different. So, use the file as-is with the "templates" folder.

Karma tests does not seem to load my Angularjs controller

I run my angular tests with karma, my application is running fine in browser, but tests fails and I am suspecting wrong settings.
Here are the controllers and tests :
// app/scripts/controllers/main.js
'use strict';
angular.module('GloubiBoulgaClientApp')
.controller('MainCtrl', function ($scope) {
});
Here is the test file :
'use strict';
describe('Controller: MainCtrl', function () {
// load the controller's module
beforeEach(module('GloubiBoulgaClientApp'));
var MainCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
MainCtrl = $controller('MainCtrl', {
$scope: scope
});
}));
it('should attach a list of awesomeThings to the scope', function () {
expect(true).toBe(true);
});
});
The karma conf
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: [
'app/bower_components/angular/angular.js',
'app/bower_components/angular-mocks/angular-mocks.js',
'app/bower_components/angular-resource/angular-resource.js',
'app/bower_components/angular-cookies/angular-cookies.js',
'app/bower_components/angular-sanitize/angular-sanitize.js',
'app/scripts/*.js',
'app/scripts/**/*.js',
'test/mock/**/*.js',
'test/spec/**/*.js'
],
// list of files / patterns to exclude
exclude: [],
// web server port
port: 8080,
// 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: true,
// 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: false
});
};
The error ouput
PhantomJS 1.9.2 (Linux) Controller: MainCtrl should attach a list of awesomeThings to the scope FAILED
Error: [ng:areq] Argument 'MainCtrl' is not a function, got undefined
http://errors.angularjs.org/1.2.8-build.2094+sha.b6c42d5/ng/areq?p0=MainCtrl&p1=not%20a%20function%2C%20got% 2
0undefined
at assertArg (--obfuscated-path--GloubiBoulga/GloubiBoulgaClient/app/bower_components/angular/angula
r.js:1362)
at assertArgFn (--obfuscated-path--GloubiBoulga/GloubiBoulgaClient/app/bower_components/angular/angu
lar.js:1373)
at --obfuscated-path--GloubiBoulga/GloubiBoulgaClient/app/bower_components/angular/angular.js:6763
at --obfuscated-path--GloubiBoulga/GloubiBoulgaClient/test/spec/controllers/main.js:15
at invoke (--obfuscated-path--GloubiBoulga/GloubiBoulgaClient/app/bower_components/angular/angular.j
s:3704)
at workFn (--obfuscated-path--GloubiBoulga/GloubiBoulgaClient/app/bower_components/angular-mocks/angular -mocks.js:2120)
I am wondering why this happen, I tried to find some documentation about the karma initialization with angularjs. But the most documentation I found is only dummy tutorial that are repeating the same pattern ( like the dummy todo list, but with phones ... )
It seem that $controllerProvide.register fails to resolve my controllers name.
But Directives tests are working correctly ...
Thanks for your attention.
Edit Notes : I replaced the controller PersonCtrl by MainCtrl in this thread because It was confusing people about where to look. Now MainCtrl is the simpliest failing example I found.
This issue is only affecting my controllers, ( all of them ), but tests for Services and Directives are working as expected
I solved my problem, I've spent nearly a week to figure why this was not working.
I'd like to warn you, that Karma Stacktrace and error reports, even in debug mode, were not showing clues and were mainly missleading.
I've spent time in javascript debugger jumping frame to frame, to understand why my controllers where not loaded. ( Inspecting Angular's controllers register, shown it was empty)
While digging in my directories I've found a *.js that were not loaded in the index in production but by the globbing pattern in tests.
It was my old http_interceptor service that I moved but did not trashed the file.
Removing this buggy file fixed the weird Karma/Jasmine/Angular behaviour.
Lesson learned :
Do not trust tests output ( but what should I trust then ? ).
Remove files you are not using/testing.
Thanks to everyone who tryied to solve this issue.
i think the main problem is coming from the karma conf :
files: [
'app/bower_components/angular/angular.js',
'app/bower_components/angular-mocks/angular-mocks.js',
'app/bower_components/angular-resource/angular-resource.js',
'app/bower_components/angular-cookies/angular-cookies.js',
'app/bower_components/angular-sanitize/angular-sanitize.js',
'app/scripts/*.js',
'app/scripts/**/*.js',
'app/scripts/**/**/*.js',
'test/mock/**/*.js',
'test/spec/**/*.js'
],
removing the * and specifying files one by one in the correct order, because if one is loaded before another it can break.
Edit : Add your files in the same order as your index.html
looking at this I'm wondering if the error message is confusing things.
in the stack trace i can see
TypeError: 'undefined' is not an object (evaluating 'scope.awesomeThings.length')
and from the example it does seem as though you have not defined any properties on the scope in your controller.
do you still have the problem if you add
$scope.awesomeThings = [];
to your controller?
If you're using the latest angular and also using the angular-route module, you should include the angular-route script in the karma conf file too:
files: [
'app/bower_components/angular/angular.js',
'app/bower_components/angular-route/angular-route.js',
'app/bower_components/angular-mocks/angular-mocks.js',
'app/bower_components/angular-resource/angular-resource.js',
'app/bower_components/angular-cookies/angular-cookies.js',
'app/bower_components/angular-sanitize/angular-sanitize.js',
'app/scripts/*.js',
'app/scripts/**/*.js',
'app/scripts/**/**/*.js',
'test/mock/**/*.js',
'test/spec/**/*.js'
],
I had this problem and adding it to the karma file did the trick.

Resources