我想测试这个 Controller
/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];
};
...
}
]);
自从编写测试后,我已经更改了 Controller 。一些常量已移至 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));
...
});
});
我如何注入(inject) angular.module('c2gyoApp').value('smConfig'){}
和 angular.module('c2gyoApp').constant('stadtmobilRates') {}
进入测试?我正在使用标准的 yeoman 布局。 karma.conf 文件包含所有必要的 .js 文件,所以这只是一个在何处注入(inject) Angular 元素的问题。
最佳答案
因为您要添加 c2gyoApp
模块:
beforeEach(module('c2gyoApp'));
在该模块中注册的所有内容都应该是可注入(inject)的。所以,这应该有效:
var smConfig, stadtmobilRates;
beforeEach(inject(function($controller, $rootScope, _smConfig_, _stadtmobilRates_) {
scope = $rootScope.$new();
DatetimepickerCtrl = $controller('DatetimepickerCtrl', {
$scope: scope
});
smConfig = _smConfig_;
stadtmobilRates = _stadtmobilRates_;
}
关于javascript - 如何将 Angular 值和 Angular 常数注入(inject) karma 单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28432959/