Search code examples
javascriptunit-testingjasminemarionettekarma-jasmine

Underscore error when running karma + jasmine test


I'm new with frontend code testing. I have a strange error when running karma + jasmine tests over my js MarionetteJs app. I think it might be because underscore templates are not loaded yet when I'm defining my Marionette views.

My karma.conf.js:

'use strict';

module.exports = function (config) {
    config.set({
        basePath: '',
        frameworks: ['browserify', 'jasmine-ajax', 'jasmine-jquery', 'jasmine'],
        exclude: ["*.jst"],
        logLevel: 'LOG_DEBUG',
        reporters: ['progress'],
        preprocessors: {
            'tests/unit/**/test_*.js': ['browserify']
        },
        colors: true,
        browsers: ['PhantomJS'],
        singleRun: true,
        autoWatch: false,
        plugins: [
            'karma-coverage',
            'karma-browserify',
            'karma-jasmine-ajax',
            'karma-jasmine-jquery',
            'karma-jasmine',
            'karma-junit-reporter',
            'karma-phantomjs-launcher'
        ],
        browserify: {
            debug: true,
            transform: [
                'browserify-jst',
                'browserify-shim',
                'browserify-istanbul'
            ]
        },
        files: [
            'http://code.jquery.com/jquery-1.11.2.min.js',
            'tests/unit/**/test_*.js'
        ]
    });
};

This is just a dummy test that I'm trying to run:

'use strict';

var CompanyListView = require('../../company_list.js');

$(function () {
    describe("A page", function () {
        it("contains login form", function () {            
            expect(true).toBe(true);
        });
    });
});

Error happens during requiring company_list.js file:

PhantomJS 1.9.8 (Linux 0.0.0) ERROR
  TypeError: 'undefined' is not a function (evaluating 'text.replace')
  at /tmp/082eb28c15575edda85ae0f9ce2019a6.browserify:17883:0 <- node_modules/underscore/underscore.js:1431:0

company_list.js:

var $ = require('jquery');
var _ = require('underscore');
var Backbone = require('backbone');
var Marionette = require('backbone.marionette');

var tplCompany = require('../templates/company_list.jst');

module.exports = Marionette.CompositeView.extend({
    template: _.template(tplCompany, {variable: 'data'}),
});

What I'm doing wrong?

Thanks for your help.


Solution

  • The solution was in karma.conf.js:

    transform: [
          'browserify-jst',
          'browserify-shim',
          'browserify-istanbul'
    ]
    

    Must be:

    transform: [
        ['stringify', {extensions: ['.html', '.jst'], minify: false}],
        'browserify-shim',
        'browserify-istanbul'
    ]