如何将角度值和角度常数注入业力单元测试?

时间:2015-02-10 13:31:32

标签: javascript angularjs unit-testing karma-runner yeoman

我想测试这个控制器

/controllers/datetimepicker.js

angular.module('c2gyoApp')
  .value('smConfig', {
    rate: 'A',
    tariff: 'classic'
  })
  .controller('DatetimepickerCtrl', [
    '$scope',
    'stadtmobilRates',
    'smConfig',
    function($scope, stadtmobilRates, smConfig) {
      ...
      $scope.getCurrentRate = function(rate, tariff) {
        // studi and classic have the same rates
        if (tariff === 'studi') {
          tariff = 'classic';
        }
        return stadtmobilRates[tariff][rate];
      };
      ...
    }
  ]);

自从我编写测试以来,我已经更改了控制器。一些常量已移至angular.module('c2gyoApp').value('smConfig'){},我还需要来自angular.module('c2gyoApp').constant('stadtmobilRates'){}的常量:

/services/stadtmobilrates.js

angular.module('c2gyoApp')
  .constant('stadtmobilRates', {
    'classic': {
      'A': {
        'night': 0,
        'hour': 1.4,
        'day': 21,
        'week': 125,
        'km000': 0.2,
        'km101': 0.18,
        'km701': 0.18
      },
      ...
});

这是我到目前为止的测试:

/test/spec/controllers/datetimepicker.js

describe('Controller: DatetimepickerCtrl', function() {

  // load the controller's module
  beforeEach(module('c2gyoApp'));

  var DatetimepickerCtrl;
  var scope;

  // Initialize the controller and a mock scope
  beforeEach(inject(function($controller, $rootScope) {
    scope = $rootScope.$new();
    DatetimepickerCtrl = $controller('DatetimepickerCtrl', {
      $scope: scope
    });
  }));

  it('should calculate the correct price', function() {
    expect(scope.price(10, 10, 0, 0, 'A', 'basic')
      .toFixed(2)).toEqual((18.20).toFixed(2));
      ...
  });
});

如何将angular.module('c2gyoApp').value('smConfig'){}angular.module('c2gyoApp').constant('stadtmobilRates'){}注入测试?我正在使用标准的自耕农布局。 karma.conf文件包含所有必需的.js文件,所以这只是一个注入角元素的问题。

1 个答案:

答案 0 :(得分:15)

由于您要添加c2gyoApp模块:

beforeEach(module('c2gyoApp'));

该模块内注册的所有内容都应该是可注射的。所以,这应该有效:

var smConfig, stadtmobilRates;

beforeEach(inject(function($controller, $rootScope, _smConfig_, _stadtmobilRates_) {

   scope = $rootScope.$new();
   DatetimepickerCtrl = $controller('DatetimepickerCtrl', {
      $scope: scope
   });
   smConfig = _smConfig_;
   stadtmobilRates = _stadtmobilRates_;
}
相关问题