karma: text! plugin could not load the HTML template during test

It appear when using Karma with Require.js, it cannot load text! plugin. I am getting

Error: /base/app/assets/javascripts/src/client/templates/show.html HTTP status: 404

But if I change the file extension to show.js, it can be loaded. It appear that it only accept JavaScript file?

Here is the proof-of-concept repo to product this: https://github.com/mech/front_end_demo

About this issue

  • Original URL
  • State: closed
  • Created 11 years ago
  • Comments: 21 (1 by maintainers)

Most upvoted comments

FWIW: I’m using karma 0.12.16 and karma-requirejs 0.2.2 and for me it was just enough to add this line to karma.conf.js to successfully load a template via the text plugin and prevend a 404:

(files: [{pattern: 'templates/*.html', included: false}])

@ievgenneiman:

text! requirejs can’t load html in Karma solution

  • Root cause: can’t include html file. Karma includes files as <script src="...">, so this would lead into “unexpected token” error.
  • That’s why by default Karma comes with html2js preprocessor which puts the HTML content into a global __html__['some.html']. This is why Karma serves test.html.js instead of test.html.
  • Solution step one: disable the preprocessor
preprocessors: {}
  • Solution step two: configure the html files to NOT be incldued
files: [{pattern: 'templates/*.html', included: false}]
  • Then, Karma will serve the templates/x.html, but not include it, so that require.js can fetch it on its own.
  • requirejs configuration: Use TestSuite.js to load needed test cases files. Note: If use deps to load test cases, could meet with unexpected < error. So use a module to load all test cases.
requirejs.config({
    //Karma serves files from '/base'
    baseUrl: 'base',

    // add text! plugin
    paths : { 
        text  : 'lib/text'
    },

    // ask Require.js to load these files (all our tests)
    //deps: tests,

    // start test run, once Require.js is done
    callback: function() {
        console.log('start to load test cases!');
        require(['test/TestSuite'], function() {
            console.log('load all test cases done!');
            window.__karma__.start();
        });
    }
});

  • TestSuite.js
define(['test/active/test'], function() {
    console.log('TestSuite');
});