Angularjs 如何在karma jasmine测试用例中注入外部提供者?

Angularjs 如何在karma jasmine测试用例中注入外部提供者?,angularjs,karma-runner,karma-jasmine,Angularjs,Karma Runner,Karma Jasmine,我不熟悉角度和业力测试用例 对于我的应用程序,我使用Angularjs和SweetAlert来显示警报。() 下面是获取http请求状态的代码,我在SweetAlert中显示http请求状态 (function () { 'use strict'; angular .module('app.admin') .controller('TestController', TestController); TestController.$inject = ['$scope','$ht

我不熟悉角度和业力测试用例

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

下面是获取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
  })
}
'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);
  });

});
测试规范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
  })
}
'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
F:\Projects\Angular\NewSample\Development\test\master>gulp测试
[13:06:40]使用gulpfile F:\Projects\Angular\NewSample\Development\test\master\gulpfile.js
[13:06:40]开始“测试”。。。
警告'start'方法自0.13以来已被弃用。它将在0.14中删除。请
使用
服务器=新服务器(配置,[完成])
server.start()
相反
27 01 2016 13:06:40.250:信息[业力]:业力v0.13.19服务器于启动http://lo
主持人:9876/
27 01 2016 13:06:40.261:信息[启动器]:启动浏览器Chrome
27 01 2016 13:06:41.793:信息[Chrome 47.0.2526(Windows 8.1 0.0.0)]:已连接到
n插座/HMYJFO5x2TLTKMMHAAA,id为83740230
Chrome 47.0.2526(Windows 8.1 0.0.0)日志:“本地主机”
Chrome 47.0.2526(Windows 8.1 0.0.0)日志:“本地主机”
Chrome 47.0.2526(Windows 8.1 0.0.0)测试控制器应告知hi失败

错误:[$injector:unpr]未知提供程序:SweetAlertProvider在注入之前,您应该添加此行

beforeEach(module('_SweetAlert_'));
并更改karma.config.js文件路径,如下所示


bower\u components/sweetalert/dist/sweetalert.min.js
app/bower\u components/sweetalert/dist/sweetalert.min.js
在注入之前,您应该添加此行

beforeEach(module('_SweetAlert_'));
并更改karma.config.js文件路径,如下所示

bower\u components/sweetalert/dist/sweetalert.min.js
app/bower\u components/sweetalert/dist/sweetalert.min.js
试试这个。(这里我使用了
$injector
来注入
sweetalert

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


我在每个模块(“SweetAlert”)之前添加了这个;在myapp模块之后,会出现类似SweetAlert不可用的抛出错误。我认为您的配置文件url是错误的。将此
bower\u components/sweetalert/dist/sweetalert.min.js
更改为
app/bower\u components/sweetalert/dist/sweetalert.min.js
我的路径是正确的,只有@balamurugan-r我的项目结构是project\u name-->app-->maste-->server-->供应商,就像这样我发现了问题,sweetalert使用两个js文件,我只包含一个文件,现在它工作得很好。谢谢大家。我在每个模块(“SweetAlert”)之前都添加了这个;在myapp模块之后,会出现类似SweetAlert不可用的抛出错误。我认为您的配置文件url是错误的。将此
bower\u components/sweetalert/dist/sweetalert.min.js
更改为
app/bower\u components/sweetalert/dist/sweetalert.min.js
我的路径是正确的,只有@balamurugan-r我的项目结构是project\u name-->app-->maste-->server-->供应商,就像这样我发现了问题,sweetalert使用两个js文件,我只包含一个文件,现在它工作得很好。谢谢大家。