【问题标题】:How to inject External Providers in karma jasmine test case?如何在 karma jasmine 测试用例中注入外部提供者?
【发布时间】:2016-05-04 01:17:25
【问题描述】:

我是 Angular 和 karma 测试用例的新手。

对于我的应用程序,我使用 Angularjs 和 SweetAlert 来显示警报。 (SweetAlert Plugin here)

下面是我获取 http 请求状态的代码,我在 SweetAlert 中显示 http 请求状态

(function () {
'use strict';

angular
    .module('app.admin')
    .controller('TestController', TestController);

TestController.$inject = ['$scope','$http','SweetAlert'];
function TestController($scope,$http,SweetAlert) {
var vm = this;

vm.test = 'hi';
    vm.todos = [];
    vm.todo = 'Run';
    vm.status = '';

vm.GetURL = function(){
    $http.get("some url")
                    .then(function (result) {
                        vm.status = result.status;
                        SweetAlert.swal(JSON.stringify(vm.status))
                    });
};

vm.addTodo = function(){
    vm.todos.push(vm.todo);
};
vm.removeTodo = function(index){
    vm.todos.splice(index, 1);
};

}

})();

这工作正常,没有任何问题,但我需要测试我的应用程序,因为我正在使用 karma 和 jasmine 框架。下面是我的 karma.config.js 和测试文件。

karma.config.js

// Karma configuration
// Generated on Tue Jan 26 2016 21:38:16 GMT+0530 (India 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'],


    // list of files / patterns to load in the browser
    files: [
    '../app/js/base.js',
    '../global_URL.js',
    'bower_components/sweetalert/dist/sweetalert.css',
    'bower_components/sweetalert/dist/sweetalert.min.js',
    'bower_components/angular-mocks/angular-mocks.js',
    '../app/js/app.js',
    'test/spec/**/*.js'
    ],


    // list of files to exclude
    exclude: [
    ],


    // 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: false,


    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],
    plugins: [
                'karma-chrome-launcher',
                'karma-firefox-launcher',
                'karma-jasmine',
                'karma-phantomjs-launcher'
            ],


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

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  })
}

test.spec.js

'use strict';

describe('Test Controller', function () {

  // load the controller's module
  var MainCtrl,
        SweetAlert,
        URLService,
        httpcall,
        scope;
  beforeEach(module('sample'));

  /*beforeEach(inject(function(_SweetAlert_,_URLService_){
    URLService = _URLService_;
    SweetAlert = _SweetAlert_;
  }));*/

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($rootScope, $controller,$http,_SweetAlert_) {
    scope = $rootScope.$new();
    MainCtrl = $controller('TestController', {
      $scope: scope,
      httpcall : $http,
      SweetAlert : _SweetAlert_
    });
  }));

    it('should tell hi', function () {
      expect(MainCtrl.test).toBe("hi");
    });

   it('should give the status', function () {
        MainCtrl.GetURL();
      expect(MainCtrl.status).toBe(200);
    });

  it('should have no items to start', function () {
    expect(MainCtrl.todos.length).toBe(0);
  });

  it('should add items to the list', function () {
    MainCtrl.todo = 'Test 1';
    MainCtrl.addTodo();
    expect(MainCtrl.todos.length).toBe(1);
  });

  it('should add then remove an item from the list', function () {
    MainCtrl.todo = 'Test 1';
    MainCtrl.addTodo();
    MainCtrl.removeTodo(0);
    expect(MainCtrl.todos.length).toBe(0);
  });

});

但它会引发以下错误:

    F:\Projects\Angular\NewSample\Development\test\master>gulp test
    [13:06:40] Using gulpfile F:\Projects\Angular\NewSample\Development\test\master\gulpfile.js
    [13:06:40] Starting 'test'...
    WARN `start` method is deprecated since 0.13. It will be removed in 0.14. Please
     use
      server = new Server(config, [done])
      server.start()
    instead.
    27 01 2016 13:06:40.250:INFO [karma]: Karma v0.13.19 server started at http://lo
    calhost:9876/
    27 01 2016 13:06:40.261:INFO [launcher]: Starting browser Chrome
    27 01 2016 13:06:41.793:INFO [Chrome 47.0.2526 (Windows 8.1 0.0.0)]: Connected o
    n socket /#hmyJFO5x2TLTkMMHAAAA with id 83740230
    Chrome 47.0.2526 (Windows 8.1 0.0.0) LOG: 'localhost'

    Chrome 47.0.2526 (Windows 8.1 0.0.0) LOG: 'localhost'

    Chrome 47.0.2526 (Windows 8.1 0.0.0) Test Controller should tell hi FAILED
            Error: [$injector:unpr] Unknown provider: SweetAlertProvider <- SweetAle
    rt
            http://errors.angularjs.org/1.4.2/$injector/unpr?p0=SweetAlertProvider%2
    0%3C-%20SweetAlert
                at F:/Projects/Angular/NewSample/Development/test/ap
    p/js/base.js:9274:12

我不知道为什么。,我该如何解决这个问题?

为此我花了很长时间,是否可以在 karma 中包含第三方插件。

请帮助我,在此先感谢。

【问题讨论】:

    标签: angularjs karma-runner karma-jasmine


    【解决方案1】:

    试试这个。(这里我用$injector注入SweetAlert

    describe('Test Controller', function () {
      var MainCtrl,
            SweetAlert,
            URLService,
            httpcall,
            scope;
    beforeEach(module('sample'));
    beforeEach(module('SweetAlert'));
    
    beforeEach(inject(function ($injector) {
      $rootScope = $injector.get('$rootScope');
      $scope = $rootScope.$new();
      SweetAlert = $injector.get('SweetAlert');
      MainCtrl = $controller('TestController', {
        $scope: scope,
        httpcall : $http,
        SweetAlert : SweetAlert
      });
     }));
    });
    

    【讨论】:

      【解决方案2】:

      在注入之前,你应该添加这一行。

      beforeEach(module('_SweetAlert_'));
      

      并且还改变 karma.config.js 文件路径,如下所示。

      bower_components/sweetalert/dist/sweetalert.min.jsapp/bower_components/sweetalert/dist/sweetalert.min.js

      【讨论】:

      • 我添加了这个 beforeEach(module('SweetAlert'));在 myapp 模块之后,它会抛出错误,例如 SweetAlert not available
      • 我认为你的配置文件 url 是错误的。将此bower_components/sweetalert/dist/sweetalert.min.js 更改为app/bower_components/sweetalert/dist/sweetalert.min.js
      • 我的路径是正确的只有@balamurugan-r 我的项目结构是 project_name-->app-->maste-->server-->vendor like that
      • 我发现了问题,SweetAlert 使用两个 js 文件,我只包含一个文件,现在它工作正常。谢谢大家。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-21
      • 2017-09-21
      • 1970-01-01
      • 2017-12-22
      • 1970-01-01
      • 1970-01-01
      • 2013-07-17
      相关资源
      最近更新 更多