2015-02-10 87 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_; 
}