2015-02-10 71 views
9

我要測試的這款控制器如何將角度值和角常量注入業力單元測試?

/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 
     }, 
     ... 
}); 

這是迄今爲止我的測試:

/測試/規格/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'){}注入測試?我正在使用標準yeoman佈局。 karma.conf文件包含所有必需的.js文件,所以這只是向何處注入角元素的問題。

回答

13

因爲您是使用添加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_; 
}