【问题标题】:angularjs with requirejs and karma testing - inject undefinedangularjs 与 requirejs 和业力测试 - 注入未定义
【发布时间】:2014-11-07 16:03:44
【问题描述】:

我有一个项目使用 angularjs 和 requirejs 并使用 karma 进行测试。我正在尝试测试项目中的服务。

这些是我使用 angularjs、requirejs 和 karma 配置的文件。当我运行我的服务测试时,我收到此错误 TypeError: Cannot read property 'inject' of undefined。如果我注释掉测试代码中的 beforeEach 部分,一切运行正常,但在实际测试中我无法做到。

test-main.js

var allTestFiles = [], file;

for (file in window.__karma__.files) {
    if (window.__karma__.files.hasOwnProperty(file)) {
        if(/test\.js$/.test(file)) {
            allTestFiles.push(file);
        }
    }
}

require.config({
  baseUrl: '/base',

  // alias library paths
  // must set 'angular'
  paths: {

    'jquery': 'web/common/js/vendor/jquery-1.10.2/jquery-1.10.2.min',
    /* common includes */
    'angular'             : 'web/common/js/vendor/angular/angular',
    'angular-ui-router'       : 'web/common/js/vendor/angular/angular-ui-router.min',
    'angular-css-injector'      : 'web/common/js/vendor/angular/angular-css-injector',
    'angular-animate'         :   'web/common/js/vendor/angular/angular-animate.min',
    'angularAMD'            : 'web/common/js/vendor/angular/angularAMD',
    'ssss-abs-tpls'          : 'web/common/js/sandbox/ssss-abs-tpls',
    'angular-sanitize'        : 'web/common/js/sandbox/angular-sanitize',
    'modernizr'           : 'web/common/js/vendor/modernizr/modernizr',
    'scrollToPlugin'          : 'web/common/js/vendor/ScrollToPlugin/ScrollToPlugin',
    'TweenMax'            : 'web/common/js/vendor/TweenMax/TweenMax',
    'gestures'            : 'web/common/js/vendor/gestures/gestures',
     'ssss-base'            : 'web/common/js/framework/ssss.base',
    'hammer'              : 'web/common/js/framework/hammer',

    'angular-mocks'       : 'web/common/js/vendor/angular/angular-mocks',

    /* controllers,not listed*/

    /* services */
    'MyService'     : 'app/services/models/MyService',

    /* directives, not listed*/


     /* router */

     'MyApp'                 :   'app/MyApp',

     /*utils*/

     'Message'            :    'app/utils/message'

  },

  /* For angular modules that do not support AMD out of the box, specify them in shim */
  shim: {
      'angular-ui-router' : ['angular'],
      'gestures': ['angular'],
      'angular-sanitize': ['angular'],
      'angular-css-injector': ['angular'],
      'angular-animate': ['angular'],
      'ssss-session': ['angular'],
      'ssss-abs-tpls'  : ['angular','gestures','angular-sanitize'],
      'angular-mocks'  : ['angular']
  },

  /* kick start the application */
  //deps: ['eMaintenance'],
  deps: allTestFiles,

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

karma.conf.js

// Karma configuration
// Generated on Wed Nov 05 2014 15:22:19 GMT-0600 (Central Standard Time)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: './',


    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine', 'requirejs'],

    // list of files / patterns to load in the browser
    files: [
        {pattern: 'web/common/*.js', included: false}, 
        {pattern: 'web/common/**/*.js', included: false}, 
        {pattern: 'app/*.js', included: false},
        {pattern: 'app/**/*.js', included: false},
        {pattern: 'test/*.js', included:false},
        {pattern: 'test/**/*.js', included:false},
        {pattern: 'test-main.js', included: true}
    ],

    // list of files to exclude
    exclude: [
      /*requirejs paths file*/
        'app/main.js' 
    ],


    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
    },


    // 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
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    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: ['Chrome'],


    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    plugins:[
        'karma-requirejs',
        'karma-chrome-launcher',
        'karma-jasmine',
        'karma-phantomjs-launcher'
    ]

  });
};

MyService.js

define(['myApp'], function (app) {

app.register.factory("MyService",["$http","$q", function($http, $q) {

  getData:function(){

            var data = {  
                    "test1":"some data"
                };

            return {
                then:function(myFunc){
                    myFunc(data);
                }
            };
        }
    };
}]);

});

MyService.test.js

define(['angular-mocks','MyApp','MyService'],
    function (mocks, app, MyService) {

    describe('MyService test', function(){

        var service;
        beforeEach(mocks.inject(function(MyService){
            service = MyService;
        }));

        it('should do something', function(){
            expect('abc').toBe('abc');
        });

    });
});

【问题讨论】:

    标签: angularjs testing requirejs jasmine karma-runner


    【解决方案1】:

    只需拨打inject 而不是mocks.inject !它现在应该可以工作了!

    beforeEach(inject(function(MyService){
        service = MyService;
    }));
    

    【讨论】:

    • 现在我得到错误:[$injector:unpr] Unknown provider: MyServiceProvider
    • 这是不同的 - 但注入问题现在我会看看会发生什么
    • 我正在测试的服务是一个我相信的 requirejs 模块,它有一个带有依赖项的定义块,并且 app.register.factory(.....) 不确定这些信息是否有帮助.. .
    • 你也必须注入模块。更好的 xway 是创建一个像这样的角度模块: var app = angular.module('MyApp', []);然后像 app.factory() 一样注册你的工厂。在您的测试中,在您的服务之前注入您的模块: beforeEach(angular.module('MyApp'));
    猜你喜欢
    • 2016-01-09
    • 2015-03-10
    • 1970-01-01
    • 2015-04-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    • 2018-05-28
    相关资源
    最近更新 更多