Karma Jasmine测试无法从javascript文件访问Requirejs的定义模块

时间:2018-01-19 07:43:06

标签: javascript unit-testing requirejs karma-jasmine jasmine-node

I seem to be have issues importing Requirejs into my Karma/Jasmine test framework.

我正在尝试测试app.js文件,该文件包含匿名函数中的几个定义模块。

问题是:无法从app.js访问模块,尝试通过app访问模块:test-main.js中的'../ js / app'。不确定正确的方法 还需要知道我们应该按模块测试整个app.js或模块

测试时获取=> TIMESTAMP错误或执行0 0错误

需要知道在JASMINE中测试此文件的正确方法

karma.conf.js
---------------------------------
module.exports = function ( config ) {
    config.set( {

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: 'theme-avis-digital/src/main/resources/templating-kit/themes/avis-digital/',

        // frameworks to use
        frameworks: [ 'jasmine', 'requirejs' ],

        // list of files / patterns to load in the browser
        files: [
            'test/test-main.js', // this is a main file which is booting up our test
            {pattern: 'vendor/ABG.js', included: true},
            {pattern: 'vendor/utag_data.js', included: true},
            {pattern: 'vendor/jquery.min.js', included: true},
            {pattern: 'vendor/jasmine-jquery.js', included: true},
            {pattern: 'vendor/require.js', included: true},
            { pattern: 'test/**/*.js', included: false }, 
            { pattern: 'js/**/*.js', included: false } 
        ],

        // list of files to exclude
        exclude: ['js/main.js'],

        preprocessors: {
            'js/**/*.js': 'coverage'
        },

        coverageReporter : {
            type: 'html',
            dir: 'coverage/'
        },

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: [ 'progress' ],

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: [ 'PhantomJS' ],

        // set this to true when your want do to a single run, usefull to CI
        singleRun: false
    } )
};

Note: 'vendor/**/*.js', included: false => throwing error
       ABG && utag_data are dependent files
--------------------------------------------------------------------------------------------------
test-main.js
----------------------------------------------------------------------------------------------
// RequireJS deps
var deps = [];

// Get a list of all the test files to include
Object.keys( window.__karma__.files ).forEach( function ( file ) {
    if ( /(spec|test)\.js$/i.test( file ) ) {
        deps.push( file );
        console.log(deps);
    }
} );

require.config( {
    // Karma serves files under /base, which is the basePath from your config file
    baseUrl: '/base/theme-avis-digital/src/main/resources/templating-kit/themes/avis-digital/js',

    paths: {
        jquery: '../vendor/jquery.min',
        require: '../vendor/require',
        app:'../js/app'
    },

    shim: {
    jquery: { exports: 'jquery' },
    require: { exports: 'require' },
    app: { 
        exports: 'App',
        deps: ['jquery', 'require'] 
    }
  },
    // dynamically load all test files
    deps: deps,

    // we have to kickoff jasmine, as it is asynchronous
    callback: window.__karma__.start
} );

------------------------------------------------------------------------------
testfile : appSpec.js
------------------------------------------------------------------------------
define(['jquery', 'require', 'app'], function(jquery, require, App) {


    describe( 'jquery', function () {
        it( 'app is defined', function () {
            expect( jquery ).not.toBe( undefined );
        } )
        it( 'require is defined', function () {
            expect( require ).not.toBe( undefined );
        } )

        it( 'is defined', function () {
            expect( app ).not.toBe( undefined );
        } )

    } );
} );

------------------------------------------------------------------------------
main.js
--------------------------------------------------------------------------------
require.config({
  // Karma serves files under /base, which is the basePath from your config file
  baseUrl: '../theme-avis-digital/src/main/resources/templating-kit/themes/avis-digital/js',

  paths: {
    jquery: '../vendor/jquery.min',
    require: '../vendor/require',
    app:'../js/app'
  }
})

------------------------------------------------------------------------------
javascript file: app.js ( line number : 30000)
------------------------------------------------------------------------------
(function(global, define) {
  var globalDefine = global.define;
  var requirejs, require, define;
(function (undef) {
    var main, req, makeMap, handlers,
        defined = {},
        waiting = {},
        config = {},
        defining = {},
        aps = [].slice;
        function normalize(name, baseName) {
        var nameParts, nameSegment, mapValue, foundMap,
            foundI, foundStarMap, starI, i, j, part,
            baseParts = baseName && baseName.split("/"),
            map = config.map,
            starMap = (map && map['*']) || {};

        //Adjust any relative paths.
        if (name && name.charAt(0) === ".") { 
            //If have a base name, try to normalize against it,
            //otherwise, assume it is a top-level require that will
            //be relative to baseUrl in the end.
            if (baseName) {
                //Convert baseName to array, and lop off the last part,
                //so that . matches that "directory" and not name of the baseName's
                //module. For instance, baseName of "one/two/three", maps to
                //"one/two/three.js", but we want the directory, "one/two" for
                //this normalization.
                baseParts = baseParts.slice(0, baseParts.length - 1);

                name = baseParts.concat(name.split("/"));

                //start trimDots
                for (i = 0; i < name.length; i += 1) {
                    part = name[i];
                    if (part === ".") {
                        name.splice(i, 1);
                        i -= 1;
                    } else if (part === "..") {
                        if (i === 1 && (name[2] === '..' || name[0] === '..')) {
                            //End of the line. Keep at least one non-dot
                            //path segment at the front so it can be mapped
                            //correctly to disk. Otherwise, there is likely
                            //no path mapping for a path starting with '..'.
                            //This can still fail, but catches the most reasonable
                            //uses of ..
                            break;
                        } else if (i > 0) {
                            name.splice(i - 1, 2);
                            i -= 2;
                        }
                    }
                }
                //end trimDots

                name = name.join("/");
            }
        }
        ..............................

define("../../../id_build/vendor/almond", function(){});

define("jQuery", function(){});

define("underscore", (function (global) {

define('createFormError',['underscore', 'jQuery'], function ( message, supporting, direction) {

define("formHelpers", function(){});

define('modules/m_d_05_car-results',['hammer'], function (hammer) {

define('modules/m_d_08_contextual-help',['jQuery','hammer', 'matchMedia'], function (hammer) {
..................................................
.............................................................
define('modules/m_d_19_car-rental-search',['CarSearchModel', 'lookAhead', 'mapFlyout', 'datePicker', 'timePicker', 'createFormError', 'utils/custom-checkbox','utils/custom-selectbox', 'modules/m_d_23_map'], function (CarSearchModel, lookAhead, mapFlyout, datePicker, timePicker, createFormError, customCheckbox,customSelectbox, map) {
.............................................................
define('modules/m_d_42_confirmation-location',['utils/map', 'utils/custom-checkbox','createFormError'], function(Map, customCheckbox,createFormError) {
.........................................................................
)}

1 个答案:

答案 0 :(得分:0)

我认为问题可能是karma.config.js中的foreach设置为basePath,它将从该目录提供文件。然后,您将RequireJS配置中的'theme-avis-digital/src/main/resources/templating-kit/themes/avis-digital/'设置为baseUrl。由于'/base/theme-avis-digital/src/main/resources/templating-kit/themes/avis-digital/js'设置basePath,我认为RequireJS配置中的base应该只是baseUrl(或者只是'base/js'),因为已经配置了Karma从'js'目录服务。

如果您想查看使用Squire.js支持模拟依赖项的工作配置,我在此处发布了一个项目:karma-squirejs-example