使用 Jasmine 测试以 uibModal 和 lodash 作为依赖项的服务

Use Jasmine to test a service with uibModal and lodash as dependencies

这是我第一次使用 Jasmine,我已经测试了我的第一个 Factory 没有问题。

但是现在,我想测试这个服务:

angular.module('Questions', [])
.service('QuestionsService', function($uibModal, $log, _) { 
  ... 
}

$uibModal 来自 UI Bootstrap(参见 here)并且 _ 是 Lodash。

到目前为止,我的 Jasmine 测试是:

describe('Service: QuestionsService', function() {

    var QuestionsService;

    beforeEach(inject(function(_QuestionsService_) {
      QuestionsService = _QuestionsService_;
    }));

    ...
}

当我尝试(grunt 测试)时,出现以下错误:

Error: [$injector:unpr] Unknown provider: $uibModalProvider <- $uibModal <- QuestionsService

在某些时候我也有:

Error: [$injector:unpr] Unknown provider: _Provider <- _ <- QuestionsService

如果有帮助,我的 Karma conf 是:

module.exports = function(config) {
  'use strict';
  config.set({
    autoWatch: true,
    basePath: '../',

    frameworks: [
      "jasmine"
    ],

    // list of files / patterns to load in the browser
    files: [
      // bower:js
      'bower_components/jquery/dist/jquery.js',
      'bower_components/lodash/lodash.js',
      'bower_components/angular/angular.js',
      'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap.js',
      'bower_components/angular-animate/angular-animate.js',
      'bower_components/angular-cookies/angular-cookies.js',
      'bower_components/angular-resource/angular-resource.js',
      'bower_components/angular-route/angular-route.js',
      'bower_components/angular-sanitize/angular-sanitize.js',
      'bower_components/angular-touch/angular-touch.js',
      'bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
      'bower_components/angular-mocks/angular-mocks.js',
      // endbower
      "app/scripts/**/*.js",
      "test/mock/**/*.js",
      "test/spec/**/*.js",
    ],
    exclude: [
    ],
    port: 8080,
    browsers: [
      "PhantomJS"
    ],
    plugins: [
      "karma-phantomjs-launcher",
      "karma-jasmine"
    ],
    singleRun: false,
    colors: true,
    logLevel: config.LOG_INFO,
  });
};

该应用的模块未包含在测试中。 QuestionService 的重构测试将是:

describe('Service: QuestionsService', function() {

    var QuestionsService;

    // The module needs to be included in the test.
    beforeEach(module('boardgameApp'));

    beforeEach(inject(function(_QuestionsService_) {
      QuestionsService = _QuestionsService_;
    }));

    ...
}

以防其他人发现。为了解决测试指令控制器时的错误,我模拟了 $uibModal 服务,概念上是这样的:

describe('Service: QuestionsService', function() {

    var controller;

    beforeEach(inject(function($controller) {
        controller = $controller('controllerName', {
            $uibModal : {}
        });
    }));

    ...
}

如果您正在针对与之交互的控制器函数编写测试,$uibModal 可能需要不仅仅是一个空对象。