如何在业力茉莉花测试案例中注入外部提供者?

时间:2016-01-27 07:43:39

标签: angularjs karma-runner karma-jasmine

我是Angular和业力测试案例的新手。

对于我的应用程序,我使用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);
};

}

})();

这没有任何问题,但我需要测试我的应用程序,因为我正在使用带有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

我不知道原因。,我该如何解决这个问题?

为此,我需要长时间的工作,是否有可能在业力中包含第三方插件。

请帮助我,提前致谢。

2 个答案:

答案 0 :(得分:1)

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

beforeEach(module('_SweetAlert_'));

还可以像下面一样更改karma.config.js文件路径。

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

答案 1 :(得分: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
  });
 }));
});