[英]How to inject angular value and angular constant into karma unit test?
I want to test this controller 我想测试这个控制器
/controllers/datetimepicker.js /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];
};
...
}
]);
I have changed the controller since I wrote the tests. 自从我编写测试以来,我已经更改了控制器。 Some constants have moved to
angular.module('c2gyoApp').value('smConfig'){}
and I also need the constant from angular.module('c2gyoApp').constant('stadtmobilRates'){}
: 一些常量已移至
angular.module('c2gyoApp').value('smConfig'){}
,我还需要来自angular.module('c2gyoApp').constant('stadtmobilRates'){}
:
/services/stadtmobilrates.js /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
},
...
});
This is my test so far: 这是我到目前为止的测试:
/test/spec/controllers/datetimepicker.js /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));
...
});
});
How do I inject angular.module('c2gyoApp').value('smConfig'){}
and angular.module('c2gyoApp').constant('stadtmobilRates'){}
into the test? 如何将
angular.module('c2gyoApp').value('smConfig'){}
和angular.module('c2gyoApp').constant('stadtmobilRates'){}
注入测试? I'm using the standard yeoman layout. 我正在使用标准的自耕农布局。 The karma.conf file includes all necessary .js files, so it's just a question of where to inject the angular elements.
karma.conf文件包含所有必需的.js文件,所以这只是一个注入角度元素的问题。
Since you are adding the c2gyoApp
module with: 由于您要添加
c2gyoApp
模块:
beforeEach(module('c2gyoApp'));
Everything registered inside that module should be injectable. 在该模块内注册的所有内容都应该是可注射的。 So, this should work:
所以,这应该工作:
var smConfig, stadtmobilRates;
beforeEach(inject(function($controller, $rootScope, _smConfig_, _stadtmobilRates_) {
scope = $rootScope.$new();
DatetimepickerCtrl = $controller('DatetimepickerCtrl', {
$scope: scope
});
smConfig = _smConfig_;
stadtmobilRates = _stadtmobilRates_;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.