Giter Site home page Giter Site logo

karma-ng-html2js-preprocessor's People

Contributors

avanrielly avatar brianlenzo avatar chirayuk avatar dignifiedquire avatar isaddo avatar jandudulski avatar levithomason avatar lgalfaso avatar lucassus avatar maksimr avatar mbfisher avatar pandeiro avatar pkozlowski-opensource avatar ratbeard avatar robinroestenburg avatar sahat avatar scottohara avatar tawez avatar vikerman avatar vojtajina avatar zzo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

karma-ng-html2js-preprocessor's Issues

Can't find variable when using jspm

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.

How can I make it work with requirejs?

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

Testacular dependency question

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

prependPrefix and cacheIdFromPath doesn't allow absolute paths

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

Add info under which module was exported files

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.

Disable logging?

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.

Missing prependSufix preprocessor argument

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;

Failed to instantiate module

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

Using ng-html2js with html2js

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?

Need version bump

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?

Abililty to strip out html comments

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.

Suffix is misspelled

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?

Error logging improvement when the dev forget to install the module :)

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" ;)

Config instructions missing the bit about adding to plugins

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

!!

SyntaxError: Parse error - unexpected characters appears in the template js files

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

need a way to inject template in script tag format

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

Can't inject it into my test?

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

missing plugin error

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?

filepath.strip is not a function

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'

Add stripSufix option

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? 😃

Parse errors when using single quotes

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 """?

Usage instructions unclear

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).)

Where is the relation with karma?

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...

Peer dependency seems to be incorrect

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.

Root path for project causes basePath stripping to fail

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.

JQuery parse errors with new line escapes

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.

svg in templateUrl support

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?

Doesn't work in strictDi mode

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

Require.js?

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

karma

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

main

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

app

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

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

error:

"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

Usin html2js with require causes 'ReferenceError: Can't find variable: angular'

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;

Configurable served path

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.

Support for inline templates?

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?

html2js-preprocessor fails if templateUrl: (elem, attr) => {return template};

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?

Allow output customization

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

Angular is not defined when using requirejs

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?

Templates containing javascript:void(0) cause errors in retrieving templates

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.

Partials encoded with unicode+signature produce junk prefix

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

Module is not created for external templates

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.

html2js-preprocessor adding relative template url

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?

Module not run

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.