karma-runner / karma-ng-html2js-preprocessor Goto Github PK
View Code? Open in Web Editor NEWA Karma plugin. Compile AngularJS 1.x and 2.x templates to JavaScript on the fly.
License: MIT License
A Karma plugin. Compile AngularJS 1.x and 2.x templates to JavaScript on the fly.
License: MIT License
I'm using jspm to load angular, when I run karma, I have Can't find variable: angular
. This error is generated by the file generated by ng-html2js
.
Here is my karma.conf :
module.exports = function (config) {
const configuration = {
browsers: [
'PhantomJS'
],
basePath: '../',
singleRun: true,
autoWatch: false,
logLevel: 'INFO',
junitReporter: {
outputDir: 'test-reports'
},
frameworks: [
'phantomjs-shim',
'jspm',
'jasmine'
],
preprocessors: {
[conf.path.src('**/*.html')]: [
'ng-html2js'
]
},
ngHtml2JsPreprocessor: {},
jspm: {
config: 'jspm.config.js',
loadFiles: [
conf.path.src('app/**/*.js'),
conf.path.src('**/*.html')
]
},
plugins: [
require('karma-jasmine'),
require('karma-junit-reporter'),
require('karma-phantomjs-launcher'),
require('karma-phantomjs-shim'),
require('karma-coverage'),
require('karma-ng-html2js-preprocessor'),
require('karma-jspm')
]
};
config.set(configuration);
};
I tried to add angular
to the paths lists and also to the files list but none worked.
I'm trying to load my template when I was testing my directives, and the decent way to do that points to the great preprocessor: karma-ng-html2js-preprocessor.
My config looks like:
files: [
'test/spec/test-main.js',
{pattern: 'app/scripts/vendor/*.js', included: false},
{pattern: 'app/scripts/services/*.js', included: false},
{pattern: 'app/scripts/controllers/*.js', included: false},
{pattern: 'app/scripts/directives/*.js', included: false},
{pattern: 'test/vendor/*.js', included: false},
{pattern: 'test/spec/**/*-spec.js', included: false},
'app/views/**/*.html'
],
preprocessors: {
'app/views/**/*.html': ['ng-html2js']
},
However, I'm using requirejs(lot of pains, actually), and the karma complained that:
Chrome 31.0.1650 (Mac OS X 10.9.0) ERROR
Uncaught ReferenceError: angular is not defined
at geo/app/views/expander.html.js:1
Any ideas about how can I make it work with requirejs?
Thanks
Hi,
It seems the pre-processor depends on a version of Testacular (~0.7) that doesn't yet exist? As far I can see Testacular is at 0.6.
Am I missing something here?
thanks
John
Hi,
Unless I'm missing something, I can't seem to get absolute paths for my templates. Both prependPrefix and cacheIdFromPath strips the initial /
.
I'm using Angular in some Drupal modules and themes, and that means that they don't exist in the root but in a sub-subdirectories, and the page runs from the root with clean URLs, making relative template calls a problem.
I specify it as follows:
ngHtml2JsPreprocessor: {
prependPrefix: '/sites/all/modules/_custom/',
cacheIdFromPath: function(filepath) {
return '/sites/all/modules/_custom/' + filepath;
}
}
..but it strips the initial /
as per the following:
angular.module('sites/all/modules/_custom/list.html', []).run(function($templateCache) {
$templateCache.put('sites/all/modules/_custom/list.html',
'angular.module(\'sites/all/modules/_custom/list.html\', []).run(function($templateCache) {\n' +
' $templateCache.put(\'sites/all/modules/_custom/list.html\',\n' +
' \'<span>test</span +\n' +
' \'\');\n' +
'});\n' +
'');
});
..causing the following error:
Error: No module: /sites/all/modules/_custom/list.html
It works if I manually add a html.js file with the absolute path.
karma: v0.10.2
karma-ng-html2js-preprocessor: v0.1.0
node: v0.10.20
Currently in log i have information that some files was processed.
I want to see unter whic module are these files exported.
Now:
DEBUG [preprocessor.html2js]: Processing "/home/view/directive.html".
Proposal:
DEBUG [preprocessor.html2js]: Processing "/home/view/directive.html". Exported as 'directive.html' module.
I can't seem to be able to disable the logging output created by this preprocessor. Even if I set debug_level on karma to none it still spits out logs. I don't really get why it's necessary to output the contents of every html file that's converted rather than just the filepaths either.
When issuing a HTTP GET with arguments:
Ex. myapp/index.html?v=1.0
it fails with error:
Error: Unexpected request: GET myapp/index.html?v=1.0
adding a prependSufix in createHtml2JsPreprocessor fixes this:
...createHtml2JsPreprocessor ... {
...
var prependSufix = config.prependSufix || '';
...
return prependPrefix + filepath.replace(stripPrefix, '').replace(stripSufix, '') + prependSufix;
I am getting an annoying warning that I do not think I deserve.
npm WARN package.json [email protected] No README data
Please fix it. =D
Regards.
I configured html2js following the docs in this repo. In my karma.conf
:
ngHtml2JsPreprocessor: {
moduleName: 'test.templates'
},
And in my unit test:
beforeEach(module('test.templates'));
However when I run the test karma barfs:
Error: [$injector:modulerr] Failed to instantiate module test.templates due to:
Error: [$injector:nomod] Module 'test.templates' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.2.14/$injector/nomod?p0=test.templates
Hi Guys, I would like to use ng-html2js with html2js but I have this error when I install ng-html2js.
'undefined' is not an object (evaluating 'window.html['PATH.json']').
Some ideas about it?
Currently it just crashes, i.e.: fails with an error about failing to load the moduleName
.
I am trying to use the configuration where you pass a function to moduleName. I have verified that I am using the most recent version number and I am installing via npm. But instead of calling my method, it uses the function definition as the module name - obviously this doesn't work.
It looks like the code is implemented, but the version number has not been bumped up. When can I expect the version bump?
When converting the HTML to JS it would be really helpful to be able to strip out any comments so they are not included in the resulting JS. If this feature already exists, then it would be nice if it was more obvious how to turn that on.
We have a referer/referrer situation :)
The configuration option
stripSufix: '.ext',
is misspelled. It should be
stripSuffix: '.ext',
I guess it's worth supporting both for backwards-compatibility?
Hello,
I lost some time because I forgot to install this node mode (but using it in Karma).
The error was misleading because I saw in Karma logs:
PhantomJS 1.9.2 (Linux) ERROR
SyntaxError: Parse error
at /usr/local/hudson-data/workspace/ecom360-sibo360/src/main/webapp/view/menu.html:1
PhantomJS 1.9.2 (Linux): Executed 0 of 0 ERROR (0.351 secs / 0 secs)
For the next users, maybe there can be made a small improvement there like "you really should install the node modules preprocessor" ;)
Not knowing how everything is connected, I spent a lot of time before realizing that I needed to add this modules to karma config plugins for it to work:
config.set({
...,
plugins: [
...,
'karma-ng-html2js-preprocessor'
],
...
});
!!
Because of the replacement of new lines with \n' +\n '
, chrome craps out if the file is too large (my current file is 9000 lines long).
the template js file created by html2js preprocessor contains some strange characters that caused the error: SyntaxError: Parse error.
For example, the error message:
PhantomJS 1.9.8 (Mac OS X 0.0.0)
SyntaxError: Parse error
at http://localhost:9777/base/app/views/fido-header-reference.html.js?9ac748880914d633717d67a5ef14c1b66e6275cd:189
I looked into the file http://localhost:9777/base/app/views/fido-header-reference.html.js at line 189,
.............')[1]==='viewInvoice'}">
\n' +
Please notice that strange characters 
 appears in it. I've verified multiple files with the same error, the same strange characters appears.
Please verify and verify.
Thanks.
Frank
Probably you should mention to add karma-ng-html2js-preprocessor to the plugins array in the karma.conf.js
It didn't work for me - I kept getting the error 'Can not load "ng-html2js"' until I added 'karma-ng-html2js-preprocessor' to the plugins section of my karma.conf.
I suggest adding this important step to the instructions.
I find this library a nice idea & soling the problem.
for some reason my templates are in the script tag format, which then include & pick up by PHP.
<script type="text/ng-template" id="templateId.html">
<p>This is the content of the template</p>
</script>
with ng-html2js, the whole thing will be treated as the template itself
i.e. $templateCache.get('templateId.html') will get the script tags as well
so the approach perhaps a script tag regex is good enough
I have tried many different combinations, but I don't understand why this isn't being instantiated. Could I get some help?
Error: [$injector:modulerr] Failed to instantiate module templates due to:
Error: [$injector:nomod] Module 'templates' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
karma.conf.js:
files: [
// if you wanna load template files in nested directories, you must use this
'**/*.html'
],
preprocessors: { 'app/views/**/*.html': 'html2js' },
ngHtml2JsPreprocessor: {
// setting this option will create only a single module that contains templates
// from all the files, so you can load them all with module('foo')
moduleName: 'templates'
},
beforeEach(module('templates'));
Hi,
I got a working jasmine-karma, and just installed this after reading: https://docs.angularjs.org/guide/unit-testing, which directes here.
So I installed the plugin and setup the karma.conf.js as mentioned in the readme file.
When I run Karma I get:
Cannot load ng-html2js, it is not registered Perhaps you are missing some plugin?
Any idea why this happens?
I am leaning heavily on cacheIdFromPath to see why my files which show up in the debugger are not showing up in the tests.
I am having no problem using the commented out part to set a path (but still cannot test my directives). For some reason the path wants to go all the way back to my directory.
I was trying filepath.strip, but I keep getting an error filepath.strip is not a function. This is odd because I am copying it exactly from the documentation. Is this a bug with angular 1.5 and bard.js or is there more to setting up filepath.strip
cacheIdFromPath: function (filepath) {
//console.log('filepath',filepath);
//var cacheId = filepath.substring(filepath.indexOf('/Templates'));
//console.log('cacheid',cacheId);
var cacheId2 = filepath.strip('Templates/', ' ');
console.log('2', cacheId2);
return cacheId2;
},
moduleName: 'templatesCached'
Should work in the same way as stripPrefix
but... strips sufix. Reason? I would love to use this combining the power of template engines like haml or slim so I could create templates into template.html.haml
file and work with such config:
...
preprocessors: {
'**/*.html.haml': ['haml', 'ng-html2js']
},
ngHtml2JsPreprocessor: {
stripPrefix: 'path/to/templates/',
stripSufix: '.haml'
}
And would have access just to templates.html
inside directives or something.
Any chance for that? 😃
So when I use single quotes in my angular expressions, Lexer errors are thrown in my tests.
Would it not be a good idea for the module to replace all the single quotes with """?
It would be great to have a set of instructions outlining the exact steps needed to configure directive testing with external templates when using the "standard" AngularJS building tools/scaffolding provided via yo angular
and yo angular:directive ...
.
Using that scaffolding, and modifying the directive to use templateUrl instead of inline HTML strings, I followed the guidelines found here and in the ng-directive-testing, including all modifications in karma.conf.js and inclusion of the template path as a module in the directive test spec js file, but testing still does not work for me. I get the following error, regardless:
Error: No module: views/whateverTemplate.html
No combination of modifying stripPrefix and module names has allowed Karma/Angular to find the 'module' of my external template. Furthermore, there is not enough information here or in the aforementioned repo to even know where to look to debug this, verify that the module, or the requisite .html.js files, were created, etc.
(This is on GNU/Linux, using AngularJS 1.0.8, Karma 0.10.4 and everything else that gets installed by default via the current stable version of yeoman/yo (1.0.4).)
Tnx for something I use a lot first of all!
But this has nothing to do with Karma, why use the word 'karma' all over the place? It is confusing...
Hi.
I'm not an NPM expert, but it seems like the karma-ng-html2js-preprocessor's peer dependency is incorrect. The way it's defined (Karma >= 0.9) makes NPM download the latest version of Karma (0.11.12), which seems to be flawed right now, causing projects to fail building, even though they don't use latest version of Karma. As I understand it that dependency should be "less greedy" and require a safe, stable version of Karma.
Makes any sense?
Kind regards.
I'm mapping my project folder to a drive in windows, causing the karma configuration file to be located at a root path (Y:\
in my case). The logic of config.basePath
seems to be slightly bugged/inconsistent in this case, because basePath
contains a trailing /
(Y:/
) in this case, instead of stripping it like in other cases. So, the htmlPath
computation code, in the file.originalPath.replace(basePath + '/', '')
piece of code, causes the replacement to contain a double trailing /
(Y://
), thus failing the substitution, thus messing up the code that follows.
I have not been able to find documentation on the testacular page on how to install and use plugins and preprocessors in particular (except for the config modifications needed). Thanks!
The path - cache key needs to be configurable.
I'd been getting parse errors such as this in my unit tests
Error: Failed to execute 'setAttribute' on 'Element': '\n'' is not a valid attribute name.
This happens when I define attributes on new lines for cleaner looking html files.
`<div class="row"
some-attr="bar"
another attr="foo"
Errors are fixed by changing the html to look like
`<div class="row" some-attr="bar" another-attr="foo"
My question is why isn't the html minified before being converted to JS string? Or at least can that be an option?
Using html-minifier to minify the code before converting to JS strings works. I did a quick test.
I created directives add svg to page and can change the cololr by css.
Something like this
.directive('svgActivityLoggedIn', function () {
return {
templateUrl: 'views/svg/activity_logged_in.svg',
restrict: 'EA',
link: function postLink(scope, element) {
element.addClass('svg-activity-logged-in');
}
};
})
But when I do unit test, I get 'Error: Unexpected request: GET views/svg/activity_logged_in.svg'. Is that because karma-ng-html2js-preprocessor doesn't support non-html content, any solution?
In my angular 1.3 apps, I always use the new ng-strict-di
directive on my ng-app
, to help detect any dependencies that aren't properly annotated (and would break when minified), eg.
<html ng-app="myApp" ng-strict-di>
In addition, my test suite has a beforeEach()
block outside of any describe()
(meaning that it runs before every spec), that enables strictDi
mode, eg.
beforeEach(inject.strictDi(true));
This causes a problem when loading any templates processed into modules by ng-html2js, eg.
beforeEach(module("path/to/template.html"));
They fail with the error:
Error: [$injector:strictdi] function($templateCache) is not using explicit annotation and cannot be invoked in strict mode
The problem appears to be that module code generated by ng-html2js does not use explicit annotation style for the injected $templateCache dependency, ie.
var TEMPLATE = 'angular.module(\'%s\', []).run(function($templateCache) {\n' +
' $templateCache.put(\'%s\',\n \'%s\');\n' +
'});\n';
Although it's unlikely that test code would ever be minified (so I can understand why annotations weren't used), could I suggest properly annotating the dependencies anyway; as this will enable strictDi
mode to be enabled globally.
The proposed change would be something like:
var TEMPLATE = 'angular.module(\'%s\', []).run(["$templateCache", function($templateCache) {\n' +
' $templateCache.put(\'%s\',\n \'%s\');\n' +
'}]);\n';
Not sure if this isn't working because I'm using requirejs or because I'm doing something incorrectly, but... if it is possible to use this (karma-ng-html2js-preprocessor) with requirejs, do you see anything that I'm doing wrong?
sidenote: this question started out as being "is it possible to use this with require.js, but I just saw this thread:
and this one
...
and this one
module.exports = function (config) {
config.set({
basePath: '../',
frameworks: ['mocha', 'requirejs', 'chai'],
files: [
'public/js/*.js',
'public/js/**/*.js',
'public/tmpl/sub_dir/*.html'
],
reporters: ['mocha', 'growl', 'html', 'coverage'],
port: 9876,
colors: true,
captureTimeout: 60000,
singleRun: false,
logLevel: config.LOG_INFO,
autoWatch: true,
preprocessors: {
'public/js/**/*.js' : ['coverage'],
'public/tmpl/sub_dir/*.html' : ['ng-html2js']
},
coverageReporter: {
type : 'html',
dir: TEST_DIR + 'results/coverage/'
},
browsers: ['Chrome']
});
}
var tests = []
, regex = /(tests\/)(_.*\.js)/
, recursive = /(tests\/)(.*\/)(_.*\.js)/
, not = /(.[_])*((^(?:(?!ignore).)*)(js))/;
for (var file in window.__karma__.files) {
if (regex.test(file) || recursive.test(file) && not.test(file) ) {
tests.push(file);
}
}
require.config({
baseUrl: "/base/public/",
paths : {
"app" : "js/angular/app"
, "angular": "lib/angular/angular"
, "mocks" : "lib/angular-mocks/angular-mocks"
, 'chai': 'lib/chai'
// uncommenting this will crash karma (tried it just bc i tried a lot of things):
// , "tmpl" : "public/tmpl/sub_dir/tmpl.html"
}
, shim: {
'angular' : {'exports' : 'angular'}
, 'mocks': {
deps: ['angular']
, 'exports': 'angular.mock'
}
}
, deps: tests
, callback: window.__karma__.start
});
require([
'angular'
, 'app'
// , "tmpl"
], function(angular, app /*, tmpl */) {
"use strict";
});
define([
'angular'
], function(angular){
"use strict";
var app = angular.module('app', []);
app.directive("test", function(){
return {
restrict: "E"
, transclude: true
, scope: {}
, templateUrl: '/tmpl/sub_dir/tmpl.html'
};
});
return app;
});
define([
'angular'
, 'mocks'
, 'chai'
, 'app'
], function(
angular
, mocks
, chai
, app
) {
"use strict"
var assert = chai.assert
, expect = chai.expect
, should = chai.should
, silent = true
, injector = angular.injector ()
, module = mocks.module
, dump = mocks.dump
, $inject = mocks.inject;
describe ("app", function () {
it ("exists", function () {
expect (app).to.exist;
});
describe ("but", function () {
var scope
, elm;
beforeEach (module ('app'));
beforeEach (module ('/tmpl/sub_dir/tmpl.html'));
beforeEach (inject (function ($rootScope, $compile) {
elm = angular.element ('< test id="tester"></ test >');
scope = $rootScope;
$compile (elm) (scope);
scope.$digest ();
}));
it ("won't even get this far", function () {
expect (angular.element ("#tester")).to.exist;
});
});
});
});
✗ "before each" hook: workFn
Chrome 35.0.1916 (Mac OS X 10.8.5)
Unexpected request: GET /tmpl/sub_dir/tmpl.html
No more request expected
Error: Unexpected request: GET /tmpl/sub_dir/tmpl.html
No more request expected
at $httpBackend (/Users/meee/Sites/test/public/lib/angular-mocks/angular-mocks.js:1178:9)
at sendReq (/Users/meee/Sites/test/public/lib/angular/angular.js:8210:9)
at $http.serverRequest (/Users/meee/Sites/test/public/lib/angular/angular.js:7951:16)
at wrappedCallback (/Users/meee/Sites/test/public/lib/angular/angular.js:11408:81)
at wrappedCallback (/Users/meee/Sites/test/public/lib/angular/angular.js:11408:81)
at /Users/meee/Sites/test/public/lib/angular/angular.js:11494:26
at Scope.$eval (/Users/meee/Sites/test/public/lib/angular/angular.js:12518:28)
at Scope.$digest (/Users/meee/Sites/test/public/lib/angular/angular.js:12330:31)
at Context.<anonymous> (/Users/meee/Sites/test/tests/unit/angular/_app.js:97:17)
at Object.invoke (/Users/meee/Sites/test/public/lib/angular/angular.js:3899:17)
Error: Declaration Location
at window.inject.angular.mock.inject (/Users/meee/Sites/test/public/lib/angular-mocks/angular-mocks.js:2134:25)
at Suite.<anonymous> (/Users/meee/Sites/test/tests/unit/angular/_app.js:80:18)
at context.describe.context.context (/Users/meee/Sites/test/node_modules/mocha/mocha.js:955:10)
at Suite.<anonymous> (/Users/meee/Sites/test/tests/unit/angular/_app.js:65:5)
at context.describe.context.context (/Users/meee/Sites/test/node_modules/mocha/mocha.js:955:10)
at /Users/meee/Sites/test/tests/unit/angular/_app.js:60:3
at Object.context.execCb (/Users/meee/Sites/test/node_modules/requirejs/require.js:1654:33)
at Object.Module.check (/Users/meee/Sites/test/node_modules/requirejs/require.js:870:51)
at Object.<anonymous> (/Users/meee/Sites/test/node_modules/requirejs/require.js:1117:34)
at /Users/meee/Sites/test/node_modules/requirejs/require.js:132:23
I have a partial defined as follows -
<div class="container-fluid" style="margin-top: 15px;">
<div class="row-fluid">
<div class="span2" style="text-align: center;">
<select ng-model="mcc_region" ng-options="regions for regions in mcc_regions"></select>
</div>
<div class="span2" style="text-align: center;">
<div class="input-append date" id="dp3" data-date="{{today}}" data-date-format="yyyy-mm-dd">
<input type="text" style="width: 100px;" value="{{today}}" />
<span class="add-on"><i class="icon-th"></i></span>
</div>
</div>
<div class="span5">
<div id="slider-range"></div>
</div>
<div class="span3">
<input type="button" value="Run" ng-click="runQuery()" style="float: right;"/>
<input id="amount" style="border: 0; font-weight: bold; width: 100%; text-align: left; float: right; width: 170px;" />
</div>
</div>
</div>
Now, after html2js has finished preprocessing the file, it translates it as follows -
angular.module('main/webapp/partials/controls.html', []).run(function($templateCache) {
$templateCache.put('main/webapp/partials/controls.html',
'<div class="container-fluid" style="margin-top: 15px;">\n' +
' <div class="row-fluid">\n' +
' <div class="span2" style="text-align: center;">\n' +
' <select ng-model="mcc_region" ng-options="regions for regions in mcc_regions"></select>\n' +
' </div>\n' +
' <div class="span2" style="text-align: center;">\n' +
' <div class="input-append date" id="dp3" data-date="{{today}}" data-date-format="yyyy-mm-dd">\n' +
' <input type="text" style="width: 100px;" value="{{today}}" />\n' +
' <span class="add-on"><i class="icon-th"></i></span>\n' +
' </div>\n' +
' </div>\n' +
' <div class="span5">\n' +
' <div id="slider-range"></div>\n' +
' </div>\n' +
' <div class="span3">\n' +
' <input type="button" value="Run" ng-click="runQuery()" style="float: right;"/>\n' +
' <input id="amount" style="border: 0; font-weight: bold; width: 100%; text-align: left; float: right; width: 170px;" />\n' +
' </div>\n' +
' </div>\n' +
'</div>');
});
However, the problem is that since I am using requireJS, angular hasn't been loaded and I get an error
ReferenceError: Can't find variable: angular
at C:/.../partials/controls.html.js:1
How do I get angular loaded for this?
My karma.conf.js is defined as follows -
// Karma configuration
// Generated on Mon Jun 24 2013 11:20:44 GMT-0400 (Eastern Daylight Time)
// base path, that will be used to resolve files and exclude
basePath = '../../';
// list of files / patterns to load in the browser
files = [
JASMINE,
JASMINE_ADAPTER,
REQUIRE,
REQUIRE_ADAPTER,
{pattern:'main/webapp/components/**/*.js', included:false},
{pattern:'main/webapp/js/**/*.js', included:false},
{pattern:'test/webapp/checker/*.js', included:false},
{pattern:'test/webapp/lib/*.js', included:false},
{pattern:'test/webapp/unit/*Test.js', included:false},
{pattern: 'main/webapp/partials/**/*.html', include: false},
'test/webapp/test-main.js'
];
// generate js files from html templates
preprocessors = {
'main/webapp/partials/**/*.html': 'html2js'
};
// list of files to exclude
exclude = [
'test/webapp/server.js',
''test/webapp/karma.conf.js',
'main/webapp/js/main.js'
];
// test results reporter to use
// possible values: 'dots', 'progress', 'junit'
reporters = ['progress'];
// web server port
port = 9876;
// cli runner port
runnerPort = 9100;
// enable / disable colors in the output (reporters and logs)
colors = true;
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel = 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','Chrome'];
// If browser does not capture in given timeout [ms], kill it
captureTimeout = 60000;
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun = false;
In my web project, I use requirejs to manage javascript files, and cache AngularJS html template with karma-ng-html2js-preprocessor for test. I have some little trouble, that I find it difficult to load these generated javascript files in the test scripts. For example, cached app/views/template.tpl.html
, I can use http://localhost:9876/base/app/views/template.tpl.html.js to load the genrated javascript file. So my sepc file like this:
define([
'angular',
'angularMock',
'directives/exampleDirective',
'../views/template.tpl.html'
], function(angular){
'use strict';
// test something
});
But I want change '../views/template.tpl.html
' to 'template.tpl.html
'.
My web project structure:
/root
/app
/views
*.tpl.html //angularjs html template files
/scripts
*.js
/test
/specs
*.spec.js //javascript spec files
main-test.js
I have a solution, karma-ng-html2js-preprocessor add configs to support transforming served path. For example:
karma.conf.coffee
:
files: [
{pattern: 'app/scripts/*.js', included: false},
{pattern: 'app/views/*.tpl.html', included: false},
'main-test.js'
]
ngHtml2JsPreprocessor:
transformPath:
pattern: '/app/views/'
replacement: '/app/scripts/'
or:
files: [
{pattern: 'app/scripts/*.js', included: false},
{pattern: 'app/views/*.tpl.html', included: false},
'main-test.js'
]
ngHtml2JsPreprocessor:
transformPath: (path)->
return path.replace('/app/views/', '/app/scripts/') + '.js'
I fork karma-ng-html2js-preprocessor and add some codes to resolve these little trouble. See https://github.com/liujinxing/karma-ng-html2js-preprocessor/commit/bbbbe246fb9a4d2eb9c0e5c06fa3b0ead04f6896.
in this commit there is a TODO with the intention to remove registering as html2js
It'd be really nice to make that a TODONE :) as it conflicts with html2js
sometimes I want to use both.
right now I'm forced to use: https://github.com/kenglxn/karma-json2js-preprocessor
mentioned as a workaround.
On TravisCI this still has the old testacular name.
/cc @vojtajina
It looks like inline templating is not currently supported by the preprocessor. ie, templates inside a
script id="tpl.html" type="text/ng-template"
tag that are embedded in other HTML. Instead, the processor just lumps the entire HTML file into one object in the $templateCache. Is it possible to parse out the individual inline templates in some way or is this a future initiative?
Hi,
I'm trying to test a directive with this kind of behaviour and if I use a dynamic template I have this error:
Error: Unexpected request: GET /partials/widgets/farefinder-compact/
directives/search-criteria/templates/default.html
No more request expected
at $httpBackend (http://localhost:9876/absolute/Users/aguilaa/source/app.ryanair.com/client/vendor/angular-mocks/angular-mocks.js:1244:9)
at $httpBackend (http://localhost:9876/absolute/Users/aguilaa/source/app.ryanair.com/client/vendor/angular-mocks/angular-mocks.js:1237:11)
at p (http://localhost:9876/absolute/Users/aguilaa/source/app.ryanair.com/client/vendor/angular/angular.min.js:89:97)
at g (http://localhost:9876/absolute/Users/aguilaa/source/app.ryanair.com/client/vendor/angular/angular.min.js:86:245)
at http://localhost:9876/absolute/Users/aguilaa/source/app.ryanair.com/client/vendor/angular/angular.min.js:119:113
at n.$eval (http://localhost:9876/absolute/Users/aguilaa/source/app.ryanair.com/client/vendor/angular/angular.min.js:133:221)
at n.$digest (http://localhost:9876/absolute/Users/aguilaa/source/app.ryanair.com/client/vendor/angular/angular.min.js:130:233)
at Object.window.TestElement.create (http://localhost:9876/absolute/Users/aguilaa/source/app.ryanair.com/client/lib/test-suite.js:31:18)
at Object. (http://localhost:9876/base/widgets/farefinder-compact/directives/search-criteria/search-criteria.test.js:61:13)
at Object.e as invoke
Error: Declaration Location
at window.inject.angular.mock.inject (http://localhost:9876/absolute/Users/aguilaa/source/app.ryanair.com/client/vendor/angular-mocks/angular-mocks.js:2409:25)
at Suite. (http://localhost:9876/base/widgets/farefinder-compact/directives/search-criteria/search-criteria.test.js:57:14)
at http://localhost:9876/base/widgets/farefinder-compact/directives/search-criteria/search-criteria.test.js:3:1
Is there any way to configure the plugin to accept this kind of configuration in the templateUrl property?
I think it would be useful to provide something like templateWrapper
option, which will be able to wrap the output, it would make it possible to simplify generation of RequireJS/SystemJS/etc. modules, e.g. for loading Angular with SystemJS:
ngHtml2JsPreprocessor: {
templateWrapper: function(body) { return "import 'angular';\n" + body; }
}
https://travis-ci.org/karma-runner/karma-ng-html2js-preprocessor/builds/37848823
As far as I can see this is due to using node 0.8 which comes with npm that doesn't recognise ^
dependencies. This raises a question: what is the node version that we should be supporting in the Karma ecosystem?
I've read two issues here, but the solutions don't work for me.
When I run the karma start regularily it says:
angular is not defined
Then, when I add:
public/lib/angular/angular.js
To the files
property I get:
Warning tried to load angular twice
And I also get:
Unexpected request: GET TEMPLATEFILEPATH
Any idea how to solve this?
This is a bug in IE 9. When a template contains javascript:void(0)
the preprocessor has an issue where it won't retrieve the template. For example, an external template contains the following:
<a href="javascript:void(0)" ng-click="buttonClicked()">Click Me</a>
Karma will return an error as follows:
TypeError: Unable to get value of the property 'then': object is null or undefined
However, clicking the DEBUG button in the browser Karma is using and checking the browser's console (F12 developer tools) shows the following:
LOG: SUCCESS ButtonsDirectives NavigationDirective Should render a loading message
I can consistently reproduce this as long as javascript:void(0)
is in the template. Removing it seems to correct the issue.
For most text encodings, ng-html2js will produce an entry in the template cache containing a properly encoded string.
However, I found in the past that when using templates encoded with UTF-? + signature, the templates retain their signature when pushed into JS. So each template comes out prefixed with \ufeff. This causes no errors until trying to use the template, where angular would produce the "Uncaught SyntaxError: Unexpected token" error referred to here.
Testing again after updating shows that ng-html2js still retains the junk signature, however it no longer causes issues in most browsers. I am testing on IE8, IE10 and Chrome and only IE8 errors with "Template must have exactly one root element".
The easy solution is just to encode your files without UTF signature, but it's still a bug I guess - either in ng-html2js or in node's file libraries.
Details:
OS: Windows Server 2012
Node: v0.10.12
ng-html2js: v0.1.0
karma: 0.10.8
angular: 1.1.4
Signature erroneously appears in: IE8, IE10, Chrome (all I have tested)
Causes issues using the template in: IE8 only
I am using JSPM, so my config is a bit different from the usual examples. In my karma.config.j file I am loading the templates the following way:
...
jspm: {
loadFiles: [
'spec/**/*.spec.js',
'dist/app.js',
],
serveFiles: [
'dist/**/*.html',
'dist/**/*.js',
'dist/**/*.js.map',
],
},
...
And configuring the plugin this way:
...
preprocessors: {
'dist/**/*.html': ['ng-html2js']
},
ngHtml2JsPreprocessor: {
moduleName: 'templates'
},
...
When I run karma with debug-level logging I can see the correct templates being processed, but I can't mock them in the tests using the module name (angular.mock.module('templates')
) nor in the debugger.
For reference I am running OS X 10.10.5, Chrome 48.0.2564.97 (64-bit) and Firefox 30.0.0.
My project folder is at var/www/apps/angular/myproject
And the templates are in the templates folder under myproject.
So the template url is specified in the directive is "/template/directive.html"
So in the karma config I've written
ngHtml2JsPreprocessor: {
stripPrefix: 'var/www/apps/angular/myproject',
moduleName: "my.templates"
},
And this config works. But I don't want to specify the full path to the project in the config because for some other environment this might change. But "myproject" folder will be always there.
So I tried with stripPrefix: '*/myproject',
But it didn't work.
Please tell me how I can fix it?
I'm not sure of what's happening on my computer: I'm using ng-html2js but always get a "module is not defined". I added some logs in html2js.js: I see messages from logs before and after module.run (whether using template or single module template), but no message from logs inside module.run.
I'm on Windows and installed/updated node.js. I removed all globally installed node modules under node_modules (checked both for my user and admin just in case). I then reinstalled all my karma related modules globally (I don't have any local module for my project), but things are still not working. I'm quite at a loss, and wonder if someone already had a similar experience.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.